简体   繁体   English

循环python随机shuffle

[英]python random shuffle while loop

I'm trying to fill lists with permutations of the same initial list. 我正在尝试使用相同初始列表的排列来填充列表。 I don't understand why the following is not working. 我不明白为什么以下不起作用。

parts = [[],[]]
while len(parts[-1]) < 2:
  newval = random.choice([[1,2,3,4],[5,6,7,8]])
  for part in parts:
    random.shuffle(newval)
    part.append(newval)

Expected result would be something like: [[[6,7,8,5],[1,3,4,2]],[[5,8,6,7],[4,2,3,1]]] 预期结果如下: [[[6,7,8,5],[1,3,4,2]],[[5,8,6,7],[4,2,3,1]]]

random.shuffle works in-place and consequently modifies newval . random.shuffle工作,因此修改newval You have to make a copy when appending to part otherwise the same list (or list reference) is shuffled and stored in part . 附加到part时必须复制,否则相同的列表(或列表引用)将被洗牌并part存储。

import random

parts = [[],[]]
while len(parts[-1]) < 2:
  newval = random.choice([[1,2,3,4],[5,6,7,8]])
  for part in parts:
    random.shuffle(newval)
    part.append(newval[:])

print(parts)

possible outputs: 可能的输出:

[[[3, 1, 2, 4], [5, 7, 6, 8]], [[1, 2, 4, 3], [6, 7, 5, 8]]]
[[[1, 3, 2, 4], [4, 2, 1, 3]], [[2, 4, 3, 1], [4, 3, 2, 1]]]
[[[7, 5, 6, 8], [3, 2, 4, 1]], [[8, 5, 6, 7], [1, 4, 3, 2]]]

Because in Python everything is reference. 因为在Python中一切都是引用。 When you append the value to the array, in fact you add the reference to the place in memory where the value is stored. 将值附加到数组时,实际上是将引用添加到存储值的内存中的位置。

Say, you have assigned the list to the first element. 比如说,您已将列表分配给第一个元素。 When on the next iteration you re-shuffle this list, you change the value in the memory. 在下一次迭代中,您重新洗牌此列表,您将更改内存中的值。 Thus, the value you will when accessing the element you appended on previous step is also changed. 因此,访问上一步中附加的元素时的值也会更改。

To fix this, try appending copy.copy(newval) instead of just newval (do not forget to import copy ) 要解决此问题,请尝试附加copy.copy(newval)而不仅仅是newval (不要忘记import copy

Here is your code changed accordingly: 以下是您的代码相应更改:

import copy
parts = [[],[]]
while len(parts[-1]) < 2:
    newval = random.choice([[1,2,3,4],[5,6,7,8]])
    for part in parts:
        random.shuffle(newval)
        part.append(copy.copy(newval))

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

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