随机化两个列表并在python中维护顺序
说我有两个简单的清单,
a = ['Spears', "Adele", "NDubz", "Nicole", "Cristina"]
b = [1,2,3,4,5]
len(a) == len(b)
我想做的是将a和a随机化,但要保持顺序。 因此,类似:
a = ["Adele", 'Spears', "Nicole", "Cristina", "NDubz"]
b = [2,1,4,5,3]
我知道我可以使用以下方法来随机排列一个列表:
import random
random.shuffle(a)
但这只是将a随机化,而我想将a随机化,并保持列表b中的“随机顺序”。
希望就如何实现这一目标提供任何指导。
JohnJ asked 2020-01-13T02:54:49Z
6个解决方案
84 votes
我将两个列表合并在一起,将结果列表随机排序,然后将它们拆分。 这利用了zip()
a = ["Spears", "Adele", "NDubz", "Nicole", "Cristina"]
b = [1, 2, 3, 4, 5]
combined = list(zip(a, b))
random.shuffle(combined)
a[:], b[:] = zip(*combined)
Tim answered 2020-01-13T02:55:10Z
16 votes
使用zip,它具有可以“两种”方式工作的出色功能。
import random
a = ['Spears', "Adele", "NDubz", "Nicole", "Cristina"]
b = [1,2,3,4,5]
z = zip(a, b)
# => [('Spears', 1), ('Adele', 2), ('NDubz', 3), ('Nicole', 4), ('Cristina', 5)]
random.shuffle(z)
a, b = zip(*z)
answered 2020-01-13T02:55:29Z
12 votes
为了避免重新发明轮子,请使用sklearn
from sklearn.utils import shuffle
a, b = shuffle(a, b)
Nimrod Morag answered 2020-01-13T02:55:49Z
8 votes
请注意,Tim的答案仅适用于Python 2,不适用于Python3。如果使用Python 3,则需要执行以下操作:
combined = list(zip(a, b))
random.shuffle(combined)
a[:], b[:] = zip(*combined)
否则会出现错误:
TypeError: object of type 'zip' has no len()
Adam_G answered 2020-01-13T02:56:14Z
2 votes
另一种方法可能是
a = ['Spears', "Adele", "NDubz", "Nicole", "Cristina"]
b = range(len(a)) # -> [0, 1, 2, 3, 4]
b_alternative = range(1, len(a) + 1) # -> [1, 2, 3, 4, 5]
random.shuffle(b)
a_shuffled = [a[i] for i in b] # or:
a_shuffled = [a[i - 1] for i in b_alternative]
这是相反的方法,但是仍然可以帮助您。
glglgl answered 2020-01-13T02:56:38Z
0 votes
这是我的风格:
import random
def shuffleTogether(A, B):
if len(A) != len(B):
raise Exception("Lengths don't match")
indexes = range(len(A))
random.shuffle(indexes)
A_shuffled = [A[i] for i in indexes]
B_shuffled = [B[i] for i in indexes]
return A_shuffled, B_shuffled
A = ['a', 'b', 'c', 'd']
B = ['1', '2', '3', '4']
A_shuffled, B_shuffled = shuffleTogether(A, B)
print A_shuffled
print B_shuffled
Nadav B answered 2020-01-13T02:56:58Z