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. 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']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.