我正在尝试从文本文件中读取的现有列表的第4个元素中创建一个新列表,以获取所有元素的总和。 这是我目前拥有的,但是我无法正常工作。
mainlist = []
newlist = []
openfile = open('filename.txt', 'r')
for line in openfile:
line = line.rstrip().split()
mainlist.append(line)
for i in mainlist:
newlist.append(mainlist[i][4])
我是一个新手,所以非常感谢您。
答案 0 :(得分:1)
我们在这里
with open('source.txt', 'r') as openfile:
mainlist = [line.rstrip().split(', ') for line in openfile]
newlist = [item[3:] for item in mainlist]
print(newlist)
输出
['30', '34', '80']
openfile = open('source.txt', 'r')
mainlist = [line.rstrip().split(', ') for line in openfile]
newlist = [item[3:] for item in mainlist]
print(newlist)
输出
[['30', '30', '30'], ['34', '32', '23'], ['80', '30', '32']]