简体   繁体   中英

How can I append a text file's variables values in the corresponding index of a 2D array/list?

Code:

    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)

Output:

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

Desired Output:

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

What method can I use to reach my desired output?

The text file I used:

在此处输入图像描述

Try this:

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)

Instead of

listPressups[0][x].append(int(press_ups))

It should be

listPressups[x][1].append(int(press_ups))

You could just start with an empty array, here: listPressups and append with just a while loop as shown below.

opener = open("gymclub.txt", "r")
reader = opener.readline()
#listPressups = [["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",]]
listPressups = []
while reader!="":
    splitting=reader.split(",")
    name = splitting[0]
    press_ups = splitting[1]
    pull_ups = splitting[2]
    reader = opener.readline()
    listPressups.append(["",int(press_ups)]) #Here we append an empty string with each value
listPressups.sort(reverse=True)
print(listPressups)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM