[英]How do i add element from one list into another list?
I am trying to create a new list from the 4th element of preexisting lists that are read in from a text file in order to get the sum of all elements.我试图从从文本文件中读入的预先存在的列表的第 4 个元素创建一个新列表,以获得所有元素的总和。 This is what I currently have, but I can't get it working.这是我目前拥有的,但我无法让它工作。
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])
I am a complete novice so any help would be greatly appreciated.我是一个完整的新手,所以任何帮助将不胜感激。
Here we are我们到了
with open('source.txt', 'r') as openfile:
mainlist = [line.rstrip().split(', ') for line in openfile]
newlist = [item[3:] for item in mainlist]
print(newlist)
Outputs输出
['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)
Outputs输出
[['30', '30', '30'], ['34', '32', '23'], ['80', '30', '32']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.