简体   繁体   English

随机洗牌多个列表python

[英]Random shuffle multiple lists python

I have a set of lists in Python and I want to shuffle both of them but switching elements in same positions in both lists like我在 Python 中有一组列表,我想对它们进行混洗,但要在两个列表中的相同位置切换元素,例如

          a=[11 22 33 44] b = [66 77 88 99]
          *do some shuffeling like [1 3 0 2]* 
          a=[22 44 11 33] b = [77 99 66 88]

Is this possible?这可能吗?

Here's a solution that uses list comprehensions:这是一个使用列表推导式的解决方案:

>>> a = [11, 22, 33, 44]
>>> b = [66, 77, 88, 99]
>>> p = [1, 3, 0, 2]
>>>
>>> [a[i] for i in p]
[22, 44, 11, 33]
>>>
>>> [b[i] for i in p]
[77, 99, 66, 88]
>>>

You can use zip in concert with the random.shuffle operator:您可以将ziprandom.shuffle运算符结合使用:

a = [1,2,3,4]          # list 1
b = ['a','b','c','d']  # list 2
c = zip(a,b)           # zip them together
random.shuffle(c)      # shuffle in place
c = zip(*c)            # 'unzip' them
a = c[0]
b = c[1]
print a                # (3, 4, 2, 1)
print b                # ('c', 'd', 'b', 'a')

If you want to retain a,b as lists, then just use a=list(c[0]) .如果要将 a,b 保留为列表,则只需使用a=list(c[0]) If you don't want them to overwrite the original a/b then rename like a1=c[0] .如果您不希望它们覆盖原始的 a/b,则重命名为a1=c[0]

Expanding upon Tom's answer, you can make the p list easily and randomize it like this:扩展汤姆的答案,您可以轻松地制作 p 列表并像这样随机化它:

import random    
p = [x for x in range(len(a))]
random.shuffle(p)    

This works for any size lists, but I'm assuming from your example that they're all equal in size.这适用于任何大小的列表,但我从你的例子中假设它们的大小都是相等的。

Tom's answer:汤姆的回答:

Here's a solution that uses list comprehensions:这是一个使用列表推导式的解决方案:

a = [11, 22, 33, 44] b = [66, 77, 88, 99] p = [1, 3, 0, 2] a = [11, 22, 33, 44] b = [66, 77, 88, 99] p = [1, 3, 0, 2]

[a[i] for i in p] [a[i] for i in p]

[22, 44, 11, 33] [22, 44, 11, 33]

[b[i] for i in p] [b[i] for i in p]

[77, 99, 66, 88] [77, 99, 66, 88]

a=[11,22,33,44]
order = [1,0,3,2]                     #give the order
new_a = [a[k] for k in order]    #list comprehension that's it

You just give the order and then do list comprehension to get new list您只需下订单,然后进行列表理解即可获得新列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM