简体   繁体   中英

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?

Numpy allows inplace shuffling of array slices.

import numpy as np
a  = np.array(a)
np.random.shuffle(a[1::2])

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