mardi 19 janvier 2016

How can a two-column Python list be shuffled?

It is straightforward to shuffle a Python list:

>>> import random
>>> random.seed(100)
>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(a)
>>> a
[7, 1, 5, 6, 4, 3, 2]

How can two-column Python list be shuffled?

So, to be specific, I have a list of the following representative form:

[
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        1
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        2
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        3
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        4
    ],
    # ... etc.
]

You could imagine this as being a form of data that captures three characteristics of an event (the three high-precision numbers) in one column and has the event numbers in the second column.

I want to shuffle this two-column list such that the events with their corresponding event numbers are shuffled. Note that I do not want to shuffle the list of event characteristics. So, in this example, the result of a shuffle could be the following:

[
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        3
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        4
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        1
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        2
    ],
    # ... etc.
]

You can see that the order of the events has been changed from 1, 2, 3, 4 to 3, 4, 1, 2.

What would be a good way to do this type of shuffle?




Aucun commentaire:

Enregistrer un commentaire