[英]list inspect second item print first item in list
我正在嘗試從列表(從文件)中剖析項目
file data with name, number of goals, passes.
Luis,8,3
Montes and Kyle,10,8
Sharon, 22, 4
Nayum,3,8
至今:
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()
可能會得出:22,但我也在嘗試找到獲勝者的名字。 我嘗試建立索引,所以我可以找到值是[::]的行號,然后可以打印第一個元素...
print(xl.index(str(x)))
但它說
ValueError: '22' is not in the list
所以我什至不能到達那里。
如何找到目標最多的人?
這是我將如何讀取csv數據的方法:
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]}
現在,只要找到具有該值的最大值項number of goals
是每個列表中的第一個元素。 您可以將內置的max與關鍵功能配合使用,以查看誰贏得了比賽:
print(max(data.items(), key=lambda t: t[1][0]))
# ('Sharon', [22, 4])
使用numlist作為字典。 。 所以代碼會像
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
答案將是22 Sharon。 會照顧好重復者,或者在多個獲勝者之間並列。 為此,您可以維護獲獎者名單並附加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.