我如何洗牌对象列表?我尝试了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
其他回答
对于numpy(科学和金融应用程序的流行库),使用np.random.shuffle:
import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)
计划:写出shuffle而不依赖于库来做繁重的工作。示例:从元素0开始从头遍历列表;为它找一个新的随机位置,比如6,把0的值放到6,把6的值放到0。移动到元素1并重复此过程,如此循环到列表的其余部分
import random
iteration = random.randint(2, 100)
temp_var = 0
while iteration > 0:
for i in range(1, len(my_list)): # have to use range with len()
for j in range(1, len(my_list) - i):
# Using temp_var as my place holder so I don't lose values
temp_var = my_list[i]
my_list[i] = my_list[j]
my_list[j] = temp_var
iteration -= 1
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1.foo,a2.foo]
random.shuffle(b)
#!/usr/bin/python3
import random
s=list(range(5))
random.shuffle(s) # << shuffle before print or assignment
print(s)
# print: [2, 4, 1, 3, 0]
""" to shuffle random, set random= True """
def shuffle(x,random=False):
shuffled = []
ma = x
if random == True:
rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
return rando
if random == False:
for i in range(len(ma)):
ave = len(ma)//3
if i < ave:
shuffled.append(ma[i+ave])
else:
shuffled.append(ma[i-ave])
return shuffled