How do I shuffle a multidimensional list in Python

元气小坏坏 提交于 2019-12-11 02:28:22

问题


I know how to shuffle a simple List in Python by using the shuffle function from the random library shuffle(myList)

But how do I shuffle a multidimensional list?

myList[][]

shuffle(myList) didn't work.


回答1:


You have to shuffle the top level list, then you can map the shuffle function to the sub lists like this in Python 2

from random import shuffle 

foo = []
foo.append([1, 2, 3])
foo.append([4, 5, 6])
foo.append([7, 8, 9])

shuffle(foo)
map(shuffle, foo)

print foo

See python 2 fiddle

And like this in python 3

from random import shuffle 

foo = []
foo.append([1, 2, 3])
foo.append([4, 5, 6])
foo.append([7, 8, 9])

shuffle(foo)
for ii, sublist in enumerate(foo): 
    shuffle(foo[ii])

print(foo)

see python 3 fiddle




回答2:


Using only standard packages, the most efficient way I can think of is to unravel the array into a single list, shuffle, then reshape into a list of lists again.

import random

def shuffle2d(arr2d, rand=random):
    """Shuffes entries of 2-d array arr2d, preserving shape."""
    reshape = []
    data = []
    iend = 0
    for row in arr2d:
        data.extend(row)
        istart, iend = iend, iend+len(row)
        reshape.append((istart, iend))
    rand.shuffle(data)
    return [data[istart:iend] for (istart,iend) in reshape]

def show(arr2d):
    """Shows rows of matrix (of strings) as space-separated rows."""
    print ("\n".join(" ".join(row) for row in arr2d))

# Generate some ragged data (5 rows):

arr2d = []
for i,a in enumerate("ABCDE"):
    n = random.randint(3,7)
    arr2d.append([a+str(j) for j in range(1,n+1)])

# display original and shuffled data

print ("Original...")
show(arr2d)
print ("Shuffled...")
show(shuffle2d(arr2d))
print ("Again...")
show(shuffle2d(arr2d))

Sample output (Python 2.7):

Original...
A1 A2 A3
B1 B2 B3 B4 B5
C1 C2 C3
D1 D2 D3
E1 E2 E3 E4 E5
Shuffled...
A3 C1 E5
C3 D3 A2 E1 D1
A1 E2 C2
B5 B4 B2
B1 D2 E4 E3 B3
Again...
B2 C2 C3
B1 D2 E5 A3 D1
A1 E3 A2
B5 D3 C1
B4 E4 E1 B3 E2

The above works equally well on Python 3.4, by the way. The only version-dependent code features are print and range, and they are used agnostically.




回答3:


I had this issue with trying to randomise questions and answers while maintaining the parring within the 2D list. At the time of writing this post, I have been learning python for only 3 weeks. My noob-solution was to create a random number, then use this number to pick from the list:

a_list = [["a4", 4], ["a3", 3],["a2", 2], ["a1", 1]]
a_pick = random.randint(0,3)
a_score = (a_list[a_pick])

This method allowed me to get a random selection from my list while keep the pairings I had written




回答4:


First, import the numpy module:

import numpy as np

numpy has a method called called random.shuffle(). This method allwos you to shuffle a multi-dimensional list.

To shuffle a list using this method, you need to convert a list to a ndarray class, then pass it to random.shuffle().

>>> foo = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> foo = np.array(foo)
>>> foo
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

Now, shuffle it.

foo = np.random.shuffle(foo)

The value of foo will be something like this:

array([[1, 2, 3],
       [7, 8, 9],
       [4, 5, 6]])


来源:https://stackoverflow.com/questions/27337784/how-do-i-shuffle-a-multidimensional-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!