Python将文本拆分为列表

时间:2018-03-16 02:32:09

标签: python string list integer

我想转换此

1:a,b,c
2:d,e,f

进入这个

[[1, ['a', 'b', 'c']],[2, ['d', 'e', 'f']]]

我的代码

letters = open("letters.txt")
alist = []
for line in favmovies:
    line = line.strip().split(":")
    line[0] = int(line[0])
    alist.append(line)

但它改为

[[1, 'a,b,c'], [2, 'd,e,f']]

有人可以提供解决方案吗?

5 个答案:

答案 0 :(得分:3)

只需将数组的第二部分拆分为","。

letters = open("letters.txt")
alist = []
for line in favmovies:
    line = line.strip().split(":")
    line[0] = int(line[0])
    line[1] = line[1].split(',')
    list.append(line)

这给了我一个例子:

[1, ['a', 'b', 'c']] 
[2, ['d', 'e', 'f']]

它保留了原始代码的首要格式。

答案 1 :(得分:1)

可以使用list comprehension来完成:

代码:

data = [[int(x[0]), [y.strip() for y in x[1].split(',')]]
        for x in (line.split(':') for line in letters)]

测试代码:

letters = ['1:a, b, c', '2: d, e, f']
data = [[int(x[0]), [y.strip() for y in x[1].split(',')]]
        for x in (line.split(':') for line in letters)]
print(data)

结果:

[[1, ['a', 'b', 'c']], [2, ['d', 'e', 'f']]]

答案 2 :(得分:0)

您可以使用re来压缩解决方案:

import re
data = [re.split('\W+', i.strip('\n')) for i in open("letters.txt")]
last_data = [[int(a), b] for a, *b in data]

输出:

[[1, ['a', 'b', 'c']], [2, ['d', 'e', 'f']]]

答案 3 :(得分:0)

下面

letters=open("letters.txt").read().split("\n")
output_list=[]
for el in letters:
    output_list.append([el.split(":")[0],el.split(":")[1].split(",")])

答案 4 :(得分:0)

这是一种循环方法:

print([list(map(lambda x: x.split(','), i.strip().split(':'))) for i in open('file.txt','r')])

输出:

[[['1'], ['a', 'b', 'c']], [['2'], ['d', 'e', 'f']]]