mercredi 14 mars 2018

Using python random.choice in combination with list.append()

Lately, I've had some problems with pythons random.choice function. I would expect the example script I've added to print out a list that consists of 3 items. Each of those items should be a list that contains two integers and one string.

For example: [[1, 4, 'a'], [2, 1, 'b'], [3, 4, 'c']]

from random import choice

pair = [
[1, 2], [1, 3], [1, 4],
[2, 1], [2, 3], [2, 4],
[3, 1], [3, 2], [3, 4],
[4, 1], [4, 2], [4, 3]
]

list = [0, 0, 0]

list[0] = choice(pair)
list[0].append('a')
list[1] = choice(pair)
list[1].append('b')
list[2] = choice(pair)
list[2].append('c')

print(list)

Most of the times the script works as expected. Sometimes however, it prints out something like this:

[[3, 2, 'a', 'c'], [4, 3, 'b'], [3, 2, 'a', 'c']]

Two of the items in the list not only consist of one string too much, but they are identical for some reason. First I believed this had something to do with the append function. However when I removed the random.choice component like this:

list = [0, 0, 0]
list[0] = [1, 2]
list[0].append('a')
list[1] = [2, 3]
list[1].append('b')
list[2] = [3, 4]
list[2].append('c')

print(list)

It still worked without flaws. Same for the random.choice function, which didn't cause any problems by itself:

from random import choice

pair = [
[1, 2], [1, 3], [1, 4],
[2, 1], [2, 3], [2, 4],
[3, 1], [3, 2], [3, 4],
[3, 1], [3, 2], [4, 3],

list = [0, 0, 0]

list[0] = choice(pair)
list[1] = choice(pair)
list[3] = choice(pair)

print(list)

Next I tested what would happen when the list contained only one item and list.append and random.choice were only executed once

from random import choice

pair = [
[1, 2], [1, 3], [1, 4],
[2, 1], [2, 3], [2, 4],
[3, 1], [3, 2], [3, 4],
[4, 1], [4, 2], [4, 3]
]

list = [0]

list[0] = choice(pair)
list.append('a')

print(list)

This script behaved like I'd expect aswell. Apparently my problem only occurs when random.choice and list.append are used executed several times on different items in a list, however I don't know how to explain it. Could someone explain what's happening and how to solve it?




Aucun commentaire:

Enregistrer un commentaire