如何测试哪个子列表包含特定元素,然后打印该子列表中的元素

How to test which sublist contains a specific element, then print elements from that Sublist

文件名: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]。我已经从所有子列表中找到最大值 'points',在本例中为 35,并且希望能够识别包含该元素的子列表,然后从所述子列表中打印元素。感谢您的帮助,谢谢。

如果您只需要一个最小值或最大值,则最便宜的方法是对列表进行排序,然后获取您需要的值。

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])

已更新您的代码以执行所需的操作

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()

我在写逻辑,你可以把它放到函数中:

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