Python:字符串到列表列表 [英] Python: string to a list of lists

查看:98
本文介绍了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:

例如

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

我正在尝试使用split()创建数据结构my_data,以便在我输入时

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']

我知道您不能分割列表,所以我先split()字符串,但是我不知道如何将新列表中的字符串转换为列表,以便我获得正确的输出.

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

也许您还想将每个数字(静止字符串)转换为int,在这种情况下,我会这样做:

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]]

这篇关于Python:字符串到列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆