简体   繁体   English

如何将一个列表中的元素添加到另一个列表中?

[英]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']

In case you want all "counts" from the third column如果您想要第三列中的所有“计数”

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.

相关问题 我如何 append 从一个列表到另一个列表的匹配元素? - How do I append a matching element from a list to another list? 从一个列表输入元素以添加到另一个列表 - Input element from one list to add to another 如何使用另一个列表中的元素搜索列表中的元素? - How do I search for an element in a list using an element in another list? 如何在Django中将列表从一个视图传递到另一个视图? - How do I pass a list from one view to another in Django? 如何将值从一个列表转移到另一个列表? - How do I transfer values from one list to another? 如何在列表元素的末尾添加“和” - How do I add 'and' at the end of the list element 如何从列表中删除随机元素并将其添加到python中的另一个列表中 - How to remove a random element from a list and add it to another list in python 如何从另一个列表中的一个元素中减去列表中的所有元素? - How to subtract all elements in list from one element in another list? 如何将一个列表中的所有整数添加到另一个列表中的整数,并在Python中以相同的顺序使用不同的长度? - How do I add all integers in one list to integers on another list with different length in the same order in Python? 如果一个列表中的元素存在于 Python 中的另一个列表中,如何打印该元素? - How to print an element from one list if it exists in another list in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM