文件名:records.csv
示例文件内容:
11, Owen, 17
4, Hank, 18
77, Paul, 10
8, Ryan, 35
12, Patrick, 24
def getFileName():
fileName = input('Input File Name: ')
return fileName
def processFile(fileName):
file = open(fileName, 'r')
lines = file.readlines()
fileList = []
info = []
pts = []
for a in lines:
fileList = a.split(',')
fileList[-1] = int(fileList[-1])
info.append(fileList)
print('-----------------------------------------------')
print('##\t Player\t Points')
print('-----------------------------------------------')
for a in info:
print(a[0],'.','\t', a[1],'\t\t', a[-1], sep='')
print('-----------------------------------------------')
for a in info:
pts.append(a[-1])
maxPts = max(pts)
# Find maxPts in one of the 5 sublist, and make a brand new list of it.
print('Top Scorer:', 'Points:', maxPts)
file.close()
def main():
fileName = getFileName()
processFile(fileName)
main()
就像上面的注释中提到的那样,列表“ info”由子列表组成,每个子列表包含来自“ records.csv”文本文件的一行。因此,第一个子列表例如是['11','Owen',17]。我已经从所有子列表中找到了最大的“点”,在这种情况下为35,并且希望能够识别包含该元素的子列表,然后从该子列表中打印元素。任何帮助表示赞赏,谢谢。
答案 0 :(得分:1)
已更新代码以执行所需的操作
def getFileName():
fileName = input('Input File Name: ')
return fileName
def processFile(fileName):
file = open(fileName, 'r')
lines = file.readlines()
fileList = []
info = []
pts = []
for a in lines:
fileList = a.split(',')
fileList[-1] = int(fileList[-1])
info.append(fileList)
print('-----------------------------------------------')
print('##\t Player\t Points')
print('-----------------------------------------------')
for a in info:
print(a[0],'.','\t', a[1],'\t\t', a[-1], sep='')
print('-----------------------------------------------')
for a in info:
pts.append(a[-1])
maxPts = max(pts)
index=pts.index(maxPts) #this finds index of the element with higest score
a=info[index]
print(a[0],'.','\t', a[1],'\t\t', a[-1], sep='') #prints the list with higest score
print
# Find maxPts in one of the 5 sublist, and make a brand new list of it.
print('Top Scorer:', 'Points:', maxPts)
file.close()
def main():
fileName = getFileName()
processFile(fileName)
main()
答案 1 :(得分:0)
如果只需要一个最小值或最大值,则对列表进行排序然后再获取所需的值是最便宜的。
info = [
[0, "a", 121],
[1, "aa", 14],
[2, "b", 55]
]
print(sorted(info, key=lambda x:x[2])[0])
print(sorted(info, key=lambda x:x[2])[-1])
答案 2 :(得分:0)
我正在编写逻辑,可以将其放入函数中
f=open('records.csv','r')
filecontent = f.readlines()
lists = [line.strip('\n').split(',') for line in filecontent if line.strip('\n')]
maxpts_sublst = max(lists,key = lambda x:int(x[-1]))
print("Top scorer: {0}, Points {1}".format(*maxpts_sublst[1:]))
f.close()
输出:
Top scorer: Ryan, Points 35