I am able to successfully add to a list called donnes
elements from a list called liste_dominos
. However, it seems like I'm creating an extra level in the list.
While printing donnes
, instead of having this output :
[[[5, 3], [6, 3], [2, 0], [4, 2], [2, 2], [6, 6]]], [[[2, 1], [6, 5], [6, 4], [3, 0], [3, 3], [3, 2]]]
I would get :
[[[[5, 3], [6, 3], [2, 0], [4, 2], [2, 2], [6, 6]]], [[[2, 1], [6, 5], [6, 4], [3, 0], [3, 3], [3, 2]]]]
Thus if I get the list of each player... instead of having this output : [[5, 3], [6, 3], [2, 0], [4, 2], [2, 2], [6, 6]]
I would get : [[[5, 3], [6, 3], [2, 0], [4, 2], [2, 2], [6, 6]]]
The list donnes
should be formated as thus [[],[]]
. Each element represents a player and in its sublist, the list of dominos they hold.
Here's the code.
import random
liste_dominos = [[6, 6], [6, 5], [6, 4], [6, 3], [6, 2], [6, 1], [6, 0], [5, 5], [5, 4], [5, 3], [5, 2], [5, 1], [5, 0], [4, 4], [4, 3], [4, 2], [4, 1], [4, 0], [3, 3], [3, 2], [3, 1], [3, 0], [2, 2], [2, 1], [2, 0], [1, 1], [1, 0], [0, 0]]
random.shuffle(liste_dominos)
no_players = 2
if int(no_players) == 2:
donnes = [[] for i in range(int(no_players))]
for x in range(no_players):
donnes[x].append(liste_dominos[:6])
del liste_dominos[:6]
print(donnes[0])
print(donnes[1])
print(donnes)
The print is only there as an indication whether I get the correct result or not. I will be later on using the donnes
list to perform other operations and thus need to get it in the aforementioned format.
even tho there are better approaches, what is happening is that you are appending to the list what is returned from liste_dominos[:6] as it's, and this is basically a list of the elements contained in that range which are a list returning in fact [ [...],..,[...]]
Using extend to append the inner elements of the list solves this:
import random
liste_dominos = [[6, 6], [6, 5], [6, 4], [6, 3], [6, 2], [6, 1], [6, 0], [5, 5], [5, 4], [5, 3], [5, 2], [5, 1], [5, 0], [4, 4], [4, 3], [4, 2], [4, 1], [4, 0], [3, 3], [3, 2], [3, 1], [3, 0], [2, 2], [2, 1], [2, 0], [1, 1], [1, 0], [0, 0]]
random.shuffle(liste_dominos)
no_players = 2
if int(no_players) == 2:
donnes = [[] for i in range(int(no_players))]
for x in range(no_players):
# Changed to extend instead of append
# It can be changed to += also
donnes[x].extend(liste_dominos[:6])
del liste_dominos[:6]
print(donnes[0])
> [[1, 0], [6, 5], [4, 3], [5, 2], [6, 3], [5, 5]]
print(donnes[1])
> [[5, 1], [3, 2], [4, 1], [2, 1], [3, 0], [2, 2]]
print(donnes)
> [[[1, 0], [6, 5], [4, 3], [5, 2], [6, 3], [5, 5]], [[5, 1], [3, 2], [4, 1], [2, 1], [3, 0], [2, 2]]]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments