首页 > 解决方案 > 如何在二维数组/列表的相应索引中附加文本文件的变量值?

问题描述

代码:

    opener = open("gymclub.txt", "r")
    reader = opener.readline()
    listPressups = [["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",]]
    while reader!="":
        splitting=reader.split(",")
        name = splitting[0]
        press_ups = splitting[1]
        pull_ups = splitting[2]
        reader = opener.readline()
        for x in range(1,12):
            listPressups[0][x].append(int(press_ups))
    listPressups.sort(reverse=True)
    print(listPressups)

输出:

Traceback (most recent call last):
  File "C:/Users/Nutzer/Desktop/Python/practice_NEA/index.py", line 36, in <module>
    listPressups[0][x].append(int(press_ups))
IndexError: list index out of range

期望的输出:

[["",75],["",74],["",73],["",67],["",66],["",58],["",45],["",33],["",30],["",25],["",10],["",8]]

我可以使用什么方法来达到我想要的输出?

我使用的文本文件:

在此处输入图像描述

标签: python

解决方案


尝试这个:

opener = open("gymclub.txt", "r")
listPressups = []
for line in opener.readlines():
    press_ups = int(line.split(",")[1])
    listPressups.append(["", press_ups])
listPressups.sort(reverse=True)
opener.close()
print(listPressups)

推荐阅读