Python列表不在循环中洗牌 [英] Python list does not shuffle in a loop

查看:177
本文介绍了Python列表不在循环中洗牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 导入随机
$ b $我试图创建一个随机的键列表b键= ['1','2','3','4','5']
random.shuffle(键)
打印键

这个工作非常完美。然而,如果我把它放在一个循环中并捕获输出:

  a = [] 
for x in range (key)



我得到了10次同样的洗牌?!显然这里有一些根本性的错误...在此先感谢。

解决方案

问题是你正在洗牌,然后将列表的引用添加到组合列表中。因此,你最终以相同的列表结构10次。
根本变化是在追加列表之前,必须复制列表。



这是一个更为pythonic

 
导入随机

def shuffleACopy(x):
b = x [:] #复制密钥
random.shuffle(b)#洗牌副本
返回b#返回副本

keys = [1,2,3,4,
= [shuffleACopy(keys)for x in range(10)]
print(a)


I'm trying to create an randomized list of keys by iterating:

import random

keys = ['1', '2', '3', '4', '5']
random.shuffle(keys)
print keys

This works perfect. However, if I put it in a loop and capture the output:

a = []
for x in range(10):
    random.shuffle(keys)
    a.append(keys)

I am getting 10 times of the same shuffle?! Obviously something is fundamentally wrong here... Thanks in advance.

解决方案

The problem is that you are shuffling the list in place and then adding the reference of the list to the combined list. Thus you end up with same list structure 10 times. "Fundamental change" is that the list has to be copied before appending it.

Here is a bit more "pythonic" way of achieving the same result with list comprehension.

import random

def shuffleACopy(x):
        b = x[:] # make a copy of the keys
        random.shuffle(b) # shuffle the copy
        return b # return the copy

keys = [1,2,3,4,5,6,7,8]
a = [shuffleACopy(keys) for x in range(10)]
print(a)

这篇关于Python列表不在循环中洗牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆