Shuffle an array with python, randomize array item

2019-01-06 11:14发布

What's the easiest way to shuffle an array with python?

10条回答
劳资没心,怎么记你
2楼-- · 2019-01-06 11:58

In addition to the previous replies, I would like to introduce another function.

numpy.random.shuffle as well as random.shuffle perform in-place shuffling. However, if you want to return a shuffled array numpy.random.permutation is the function to use.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-06 12:00

The other answers are the easiest, however it's a bit annoying that the random.shuffle method doesn't actually return anything - it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:

    import random
    def my_shuffle(array):
        random.shuffle(array)
        return array

Then you can do lines like:

    for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):
查看更多
来,给爷笑一个
4楼-- · 2019-01-06 12:03
import random
random.shuffle(array)
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-06 12:08

Just in case you want a new array you can use sample:

import random
new_array = random.sample( array, len(array) )
查看更多
登录 后发表回答