python列表中随机两个_随机化两个列表并在python中维护顺序
隨機化兩個列表并在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
總結
以上是生活随笔為你收集整理的python列表中随机两个_随机化两个列表并在python中维护顺序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matplotlib 折线图_漂亮图表也
- 下一篇: 南通百通app教育网(南通市人民政府)