日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python列表中随机两个_随机化两个列表并在python中维护顺序

發布時間:2023/12/2 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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中维护顺序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。