简体   繁体   中英

how do I append a list with two variables to another list that already has that list in it but with different values? python

I'm doing my programming coursework, and I've come across an issue

gamecentre1 = [winnerscore, winner]


organise = []

organise.extend([gamecentre1])

from operator import attrgetter, itemgetter

sorted(organise, key= itemgetter(0))

print(organise)


f = open("gameresults.txt","w")

f.write("Here are the winners of the games: \n")

f.write(str(organise))

f.write("\n")

f.close()

I'm trying to add two variables to a list, and add that list to another list. Then, I want to organise that larger list based off of the integer variable of the sublist (the integer is the winnerscore ). But, the problem is that I haven't been able to organise them properly, and I worry that since I have to append the same list with the same variables to the larger list without overwriting the existing list in it, the larger list will just have the same values over and over again.

This is because I want to store the variables every time the program runs, without getting rid of the values of the variable from the previous game.

How do I do this?

I'm trying to add two variables to a list, and add that list to another list. Then, I want to organise that larger list based off of the integer variable of the sublist

It sounds like what you want is a nested list - a big list of small lists, such that each small list is independent of the others. The key problem in your code right now that's blocking you from accomplishing this is extend() - this is essentially list concatenation , which isn't what you want. For example,

x = [1, 2]
x.extend([3, 4])  # x == [1, 2, 3, 4]

Instead, try using append() , which adds its argument as the next value in the list. For example:

x = []
x.append([3, 4])  # [[3, 4]]
x.append([1, 2])  # [[3, 4], [1, 2]]

Now in the above example, we have a list x that's two elements long, and each of those elements is itself a list of two elements. Now we can plug that into sort :

y = sorted(x, key=lambda i: i[0])
print(y)
# [[1, 2], [3, 4]]

(the lambda i: i[0] is really just a more elegant way of what you're doing with itemgettr(0) - it's a lambda , a small inline function, that takes one argument i and returns the 0 th element of i . In this case, the i that gets passed in is one of the smaller lists).

Now you have a sorted list of smaller lists, and you can do whatever you need with them.

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