如何将一个Python列表中的单个元素拆分成多个独立元素?

0 投票
2 回答
8303 浏览
提问于 2025-04-17 14:39

我有一个.txt文件,内容是这样的:

0,Hello,01,Cooking,02,Biking,13,My Hawaii Vacation,14,Freezing weather in Iowa,0

我现在写的代码是:

a = open('wiki.txt','r')
ar = a.readlines()
biglistA = map(lambda each:each.strip('\n'), ar)

这段代码的输出结果是:

['0,Hello,0', '1,Cooking,0', '2,Biking,1', '3,My Hawaii Vacation,1', '4,Freezing weather in Iowa,0']

我希望输出能变成这样:

[['0','Hello','0'], ['1','Cooking','0'], ['2','Biking','1'], ['3','My Hawaii Vacation','1'], ['4','Freezing weather in Iowa','0']] 

最终的结果需要是一个嵌套列表,每个元素都能被引用,比如:

print newlist[1][1]

'Cooking'

这就是我想要的结果。如果有人能帮忙,我将非常感激!

2 个回答

1

这是一个奇怪的需求。我想用正则表达式可能是最好的选择:

import re
with open('wiki.txt') as f:
  s = f.read()
newlist = [triple.split(',') for triple in re.findall(r'\d,.*?,\d', s)]

或者,接着你之前的思路,直接使用列表推导式,比如:

newlist = [x.split(',') for x in biglistA]
3

看起来你需要一些类似于下面的东西:

with open('wiki.txt') as fin:
    bigListA = [ line.strip().split(',') for line in fin ]

撰写回答