簡體   English   中英

如何使用 python 打開文件,將行拆分為列表,然后在第三個列表中搜索具有最高值的行

[英]How do you open a file using python, split rows into lists and then search for the row with the highest value in the third list

我的腳本不起作用,任何建議表示贊賞...

.txt 文件有 30 行數據,其中包含名字、名字和一個兩位數的測試標記...

file = open ("testmarks.txt", "r")

for i in file:
    list = i.split()

#Get highest mark and print name

for(i) in list[2]:
    max_value = max(i)
    print('Highest mark was', max_value, 'achieved by', list[0], list[1])

你可以嘗試類似的東西

input_file = open ("testmarks.txt", "r")

lists = [row.split() for row in input_file.readlines()]

lists = sorted(lists, key=lambda row: row[2], reverse=True)

print(f'Highest mark was {lists[0][2]} achieved by {lists[0][0]} {lists[0][1]}')

根據我對您的問題的理解和如下所示的文本文件,我在下面編寫了 function。

"""
aaa abc 100
bbb xyz 90
ccc def 80
"""


def sort_on_test_mark(file):

    with open(file, "r") as f:
        test_mark_list = []
        for idx, line in enumerate(f):
            # print(idx)
            # print(line)
            l = line.split()
            # print(l)
            test_mark_list.append(l)
    test_mark_list.sort(key=lambda x : int(x[-1]), reverse=True)
    first_name = test_mark_list[0][0]
    last_name = test_mark_list[0][1]
    max_value = int(test_mark_list[0][-1])
    return max_value, first_name+last_name

# file_path of your text file
result, name = sort_on_test_mark(file_path)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM