I'm trying to dissect items from a list (from a file)
file data with name, number of goals, passes.
Luis,8,3
Montes and Kyle,10,8
Sharon, 22, 4
Nayum,3,8
So far:
filen=open("WorldData.txt", 'r')
values = []##List
for line in open(filen):
values.append(line.rstrip('\n').split(','))
xl=values
numlist=[]
for line in xl:
numlist.append(int(line[1]))#second element which are goals
x=(max(numlist))
print(x)
filen.close()
Which would give out: 22 but I'm also trying to find the name of the person who won. I tried indexing so I could find the number of the line where the value is [::] so I could then print the first element...
print(xl.index(str(x)))
but it says
ValueError: '22' is not in the list
So I can't even get there.
How can I find who made the most goals?
Here is how I would read the csv data:
import csv
data={}
with open(fn, 'r') as fin:
reader=csv.reader(fin)
header=next(reader)
for row in reader:
data[row[0]]=list(map(int, row[1:]))
print(data)
# {'Luis': [8, 3], 'Nayum': [3, 8], 'Montes and Kyle': [10, 8], 'Sharon': [22, 4]}
You can see now that you have a dict of lists
Now just find the entry that has the max value for the value number of goals
which is the first element in each list. You can use the built-in max with a key function to see who won:
print(max(data.items(), key=lambda t: t[1][0]))
# ('Sharon', [22, 4])
use numlist as dictionary. . so the code would be something like
goals = 0
numlist={}
for line in xl:
numlist[line[0]]=int(line[1])#second element witch are goals
for player in numlist:
if numlist[player] > goals:
winner = player
goals = numlist[player]
print goals, winner
answer printed would be 22 Sharon. would have take care of duplicates though or tie amongst multiple winner. for that you can maintain a list for winner and append it .
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.