打乱对象列表[重复]
- 2024-12-03 08:44:00
- admin 原创
- 162
问题描述:
如何随机排列对象列表?我试过random.shuffle
:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
解决方案 1:
random.shuffle
应该可以工作。下面是一个例子,其中对象是列表:
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
print(x)
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
注意shuffle
工作到位,并返回None
。
更一般地,在 Python 中,可变对象可以传递到函数中,并且当函数变异这些对象时,标准是返回None
(而不是变异的对象)。
解决方案 2:
正如您所了解的,就地改组是问题所在。我也经常遇到问题,而且似乎经常忘记如何复制列表。使用sample(a, len(a))
是解决方案,使用len(a)
作为样本大小。请参阅https://docs.python.org/3.6/library/random.html#random.sample以获取 Python 文档。
这是一个简单的版本random.sample()
,它将混洗的结果作为新列表返回。
import random
a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False
# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))
try:
random.sample(a, len(a) + 1)
except ValueError as e:
print "Nope!", e
# print: no duplicates: True
# print: Nope! sample larger than population
解决方案 3:
的文件random.shuffle
指出,它将
将序列x 就位打乱。
不要做:
print(random.shuffle(xs)) # WRONG!
相反,应该这样做:
random.shuffle(xs)
print(xs)
解决方案 4:
#!/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]
解决方案 5:
对于numpy
(流行的科学和金融应用库),使用np.random.shuffle
:
import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)
解决方案 6:
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']
对我来说效果很好。确保设置了随机方法。
解决方案 7:
如果您有多个列表,您可能需要先定义排列(随机排列列表/重新排列列表中的项目的方式),然后将其应用于所有列表:
import random
perm = list(range(len(list_one)))
random.shuffle(perm)
list_one = [list_one[index] for index in perm]
list_two = [list_two[index] for index in perm]
Numpy/Scipy
如果你的列表是 numpy 数组,那就更简单了:
import numpy as np
perm = np.random.permutation(len(list_one))
list_one = list_one[perm]
list_two = list_two[perm]
微处理器
我创建了一个mpu
具有consistent_shuffle
以下功能的小型实用程序包:
import mpu
# Necessary if you want consistent results
import random
random.seed(8)
# Define example lists
list_one = [1,2,3]
list_two = ['a', 'b', 'c']
# Call the function
list_one, list_two = mpu.consistent_shuffle(list_one, list_two)
请注意,mpu.consistent_shuffle
可以接受任意数量的参数。因此,您还可以使用它来打乱三个或更多列表。
解决方案 8:
对于单行代码,请使用random.sample(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]
解决方案 9:
from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())
对于您想要交换排序功能的一些应用程序来说,此替代方案可能会很有用。
解决方案 10:
在某些情况下使用 numpy 数组时,使用random.shuffle
数组中创建的重复数据。
另一种方法是使用numpy.random.shuffle
。如果你已经在使用 numpy,那么这是比通用的 更受欢迎的方法random.shuffle
。
numpy.random.shuffle
例子
>>> import numpy as np
>>> import random
使用random.shuffle
:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[1, 2, 3],
[4, 5, 6]])
使用numpy.random.shuffle
:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[7, 8, 9],
[4, 5, 6]])
解决方案 11:
当使用“foo”调用“print func(foo)”时,它将打印“func”的返回值。然而,“shuffle”的返回类型为 None,因为列表将被就地修改,因此它不打印任何内容。解决方法:
# shuffle the list in place
random.shuffle(b)
# print it
print(b)
如果您更喜欢函数式编程风格,您可能需要制作以下包装函数:
def myshuffle(ls):
random.shuffle(ls)
return ls
解决方案 12:
可以定义一个名为(与vsshuffled
含义相同)的函数sort
`sorted`
def shuffled(x):
import random
y = x[:]
random.shuffle(y)
return y
x = shuffled([1, 2, 3, 4])
print x
解决方案 13:
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
a3 = a()
a4 = a()
b = [a1,a2,a3,a4]
random.shuffle(b)
print(b)
shuffle
已经到位,所以不打印结果,即None
,而是打印列表。
解决方案 14:
您可以使用 shuffle 或 sample 。它们均来自随机模块。
import random
def shuffle(arr1):
n=len(arr1)
b=random.sample(arr1,n)
return b
或者
import random
def shuffle(arr1):
random.shuffle(arr1)
return arr1
解决方案 15:
如果您需要就地改组和操纵种子的能力,那么此代码片段将会有所帮助:
from random import randint
a = ['hi','world','cat','dog']
print(sorted(a, key=lambda _: randint(0, 1)))
请记住,“洗牌”是按随机键进行的排序。
解决方案 16:
确保您没有将源文件命名为 random.py,并且工作目录中没有名为 random.pyc 的文件。两者都可能导致您的程序尝试导入本地 random.py 文件而不是 pythons random 模块。
解决方案 17:
你可以选择这样做:
>>> A = ['r','a','n','d','o','m']
>>> B = [1,2,3,4,5,6]
>>> import random
>>> random.sample(A+B, len(A+B))
[3, 'r', 4, 'n', 6, 5, 'm', 2, 1, 'a', 'o', 'd']
如果你想返回两个列表,那么你可以将这个长列表分成两部分。
解决方案 18:
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
解决方案 19:
您可以构建一个函数,该函数以列表作为参数并返回列表的混洗版本:
from random import *
def listshuffler(inputlist):
for i in range(len(inputlist)):
swap = randint(0,len(inputlist)-1)
temp = inputlist[swap]
inputlist[swap] = inputlist[i]
inputlist[i] = temp
return inputlist
解决方案 20:
""" 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
解决方案 21:
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1.foo,a2.foo]
random.shuffle(b)
解决方案 22:
对于那些有兴趣使用索引顺序法(Ouarda 等,1997)重新排序列表的人来说:
def ISM(dList):
nList = dList.copy()
dRng = range(len(dList))
for i in dRng[:-1]:
nList[i] = dList[i+1]
nList[-1] = dList[0]
return nList
这将适用于单值列表......
valList = [1,2,3,4,5,6,7]
for l in range(len(valList)):
print(valList)
dataList = ISM(valList)
这将打印出...
[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7, 1]
[3, 4, 5, 6, 7, 1, 2]
[4, 5, 6, 7, 1, 2, 3]
[5, 6, 7, 1, 2, 3, 4]
[6, 7, 1, 2, 3, 4, 5]
[7, 1, 2, 3, 4, 5, 6]
或嵌套列表的列表......
nestedList = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
for l in range(len(nestedList)):
print(nestedList)
nestedList = ISM(nestedList)
这将打印出...
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
[[4, 5, 6], [7, 8, 9], [10, 11, 12], [1, 2, 3]]
[[7, 8, 9], [10, 11, 12], [1, 2, 3], [4, 5, 6]]
[[10, 11, 12], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
@Shantanu Sharma提供了一些很好的方法,将值列表分解为大小为 n 的嵌套列表序列。
这是我使用的方法...
valList = [1,2,3,4,5,6,7,8,9,10,11,12]
# Yield successive n-sized lists from l
def SequenceList(l, n):
# looping till length l
for i in range(0, len(l), n):
yield l[i:i + n]
nestedList = list(SequenceList(valList, 3))
这将打印出...
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
解决方案 23:
改组过程是“有放回的”,因此每个项目的出现可能会发生变化!至少当您的列表中的项目也是列表时。
例如,
ml = [[0], [1]] * 10
后,
random.shuffle(ml)
[0] 的数量可能是 9 或 8,但不正好是 10。
解决方案 24:
计划:编写 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
解决方案 25:
您可以使用它random.choices()
来随机排列列表。
TEAMS = [A,B,C,D,E,F,G,H]
random.choices(TEAMS,k = len(TEAMS))
上述代码将返回一个与之前的列表长度相同的随机列表。
解决方案 26:
它工作正常。我在这里尝试使用函数作为列表对象:
from random import shuffle
def foo1():
print "foo1",
def foo2():
print "foo2",
def foo3():
print "foo3",
A=[foo1,foo2,foo3]
for x in A:
x()
print "
"
shuffle(A)
for y in A:
y()
它打印出:foo1 foo2 foo3 foo2 foo3 foo1(最后一行的 foo 具有随机顺序)