我想转换此
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']]
有人可以提供解决方案吗?
答案 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']]]