python字符串放入列表_Python:字符串到列表列表

I'm new to python and confused about converting a string to a list. I'm unsure how to create a list within a list to accomplish the following:

Ex.

string = '2,4,6,8|10,12,14,16|18,20,22,24'

I'm trying to use split() to create a data structure, my_data, so that when I input

print my_data[1][2] #it should return 14

Stuck:

This is what I did at first:

new_list = string.split('|') #['2,4,6,8', '10,12,14,16,', '18,20,22,24']

And I know that you can't split a list so I split() the string first but I don't know how to convert the strings within the new list into a list in order to me to get the right output.

解决方案>>> text = '2,4,6,8|10,12,14,16|18,20,22,24'

>>> my_data = [x.split(',') for x in text.split('|')]

>>> my_data

[['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']]

>>> print my_data[1][2]

14

Maybe you also want to convert each digit (still strings) to int, in which case I would do this:

>>> [[int(y) for y in x.split(',')] for x in text.split('|')]

[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值