【问题标题】:Why is Shuffle Returning None为什么随机播放返回无
【发布时间】:2021-02-26 08:25:31
【问题描述】:

我正在将随机模块用于程序并且不希望列表中的项目重复,所以我使用随机播放。问题是当我运行它时,它返回 None 而不是列表中的项目。

from random import shuffle

list = ["a", "b", "c", "d"]

new_list = []

for l in list:
   n = shuffle(list)
   new_list.append(n)
print(new_list)

【问题讨论】:

  • shuffle(x)随机播放列表 x,并返回 None。

标签: python python-3.x list random shuffle


【解决方案1】:

Shuffle 是一种就地操作 - 即它对原始列表进行洗牌。您可以将代码更改为:

from random import shuffle

list = ["a", "b", "c", "d"]

new_list = []

for i in range(0, len(list)):
   shuffle(list)
   new_list.append(list)
print(new_list)

【讨论】:

    【解决方案2】:

    .shuffle() 进行适当的洗牌,@Aziz 有一个很好的答案。如果要获取返回值,请使用.sample():

    from random import sample
    
    Alist = ["a", "b", "c", "d"]
    
    new_list = []
    
    for l in Alist:
       n = sample(Alist,k=len(Alist))
       new_list.append(n)
    print(new_list)
    

    【讨论】:

      猜你喜欢
      • 2013-12-25
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 2023-01-23
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多