我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
当前回答
def shuffle(_list):
if not _list == []:
import random
list2 = []
while _list != []:
card = random.choice(_list)
_list.remove(card)
list2.append(card)
while list2 != []:
card1 = list2[0]
list2.remove(card1)
_list.append(card1)
return _list
其他回答
洗牌过程是“带替换”的,所以每一项的出现都可能发生变化!至少当项目在你的列表时也是列表。
例如,
ml = [[0], [1]] * 10
之后,
random.shuffle(ml)
[0]的数字可能是9或8,但不完全是10。
你可以使用shuffle或者sample。它们都来自于随机模块。
import random
def shuffle(arr1):
n=len(arr1)
b=random.sample(arr1,n)
return b
OR
import random
def shuffle(arr1):
random.shuffle(arr1)
return arr1
'print func(foo)'将在使用'foo'调用时打印'func'的返回值。 然而,'shuffle'的返回类型是None,因为列表将在适当的位置被修改,因此它不打印任何内容。 处理:
# shuffle the list in place
random.shuffle(b)
# print it
print(b)
如果你更喜欢函数式编程风格,你可能想要制作以下包装器函数:
def myshuffle(ls):
random.shuffle(ls)
return ls
对于一行程序,使用userandom。示例(list_to_be_shuffled, length_of_the_list)与示例:
import random
random.sample(list(range(10)), 10)
输出: [2,9,7,8,3,0,4,1,6,5]
对于numpy(科学和金融应用程序的流行库),使用np.random.shuffle:
import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)