打乱对象列表
如何打乱对象列表? 我尝试了 random.shuffle
:
import random
b = [object(), object()]
print(random.shuffle(b))
但是它输出:
None
How do I shuffle a list of objects? I tried random.shuffle
:
import random
b = [object(), object()]
print(random.shuffle(b))
But it outputs:
None
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(26)
random.shuffle
应该可以工作。 下面是一个示例,其中对象是列表:请注意,
shuffle
会就地工作,并返回None
。更一般地,在 Python 中,可变对象可以传递到函数中,当函数改变这些对象时,标准是返回 None (而不是,比如说,改变的对象)。
random.shuffle
should work. Here's an example, where the objects are lists:Note that
shuffle
works in place, and returnsNone
.More generally in Python, mutable objects can be passed into functions, and when a function mutates those objects, the standard is to return
None
(rather than, say, the mutated object).正如您所知,就地洗牌是问题所在。 我也经常遇到问题,似乎也经常忘记如何复制列表。 使用
sample(a, len(a))
是解决方案,使用len(a)
作为样本大小。 请参阅 https://docs.python.org/3.6/library/random。 html#random.sample 获取 Python 文档。这是一个使用 random.sample() 的简单版本,它将打乱的结果作为新列表返回。
As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using
sample(a, len(a))
is the solution, usinglen(a)
as the sample size. See https://docs.python.org/3.6/library/random.html#random.sample for the Python documentation.Here's a simple version using
random.sample()
that returns the shuffled result as a new list.random.shuffle
的文档指出它会不做:
相反,做:
The documentation for
random.shuffle
states that it willDon't do:
Instead, do:
对于
numpy
(科学和金融应用程序的流行库),请使用np.random.shuffle
:For
numpy
(popular library for scientific and financial applications), usenp.random.shuffle
:这对我来说可以。 确保设置随机方法。
It works fine for me. Make sure to set the random method.
如果您有多个列表,您可能需要首先定义排列(打乱列表/重新排列列表中的项目的方式),然后将其应用于所有列表:
Numpy / Scipy
如果您的列表是 numpy 数组,则更简单:
mpu
我创建了一个小实用程序包
mpu
,它具有consistency_shuffle
函数:请注意
mpu.consistency_shuffle
接受任意数量的参数。 因此,您还可以用它来洗牌三个或更多列表。If you have multiple lists, you might want to define the permutation (the way you shuffle the list / rearrange the items in the list) first and then apply it to all lists:
Numpy / Scipy
If your lists are numpy arrays, it is simpler:
mpu
I've created the small utility package
mpu
which has theconsistent_shuffle
function:Note that
mpu.consistent_shuffle
takes an arbitrary number of arguments. So you can also shuffle three or more lists with it.对于单行,请使用
random.sample(list_to_be_shuffled, length_of_the_list)
并举一个示例:输出:
[2、9、7、8、3、0、4、1、6、5]
For one-liners, use
random.sample(list_to_be_shuffled, length_of_the_list)
with an example:outputs:
[2, 9, 7, 8, 3, 0, 4, 1, 6, 5]
对于某些您想要交换排序功能的应用程序,此替代方案可能很有用。
This alternative may be useful for some applications where you want to swap the ordering function.
在某些情况下,当使用 numpy 数组时,使用 random.shuffle 会在数组中创建重复数据。
另一种方法是使用 numpy.random.shuffle。 如果您已经在使用 numpy,那么这是优于通用
random.shuffle
的首选方法。numpy.random.shuffle
示例
使用
random.shuffle
:使用
numpy.random.shuffle
:In some cases when using numpy arrays, using
random.shuffle
created duplicate data in the array.An alternative is to use
numpy.random.shuffle
. If you're working with numpy already, this is the preferred method over the genericrandom.shuffle
.numpy.random.shuffle
Example
Using
random.shuffle
:Using
numpy.random.shuffle
:当用“foo”调用时,“print func(foo)”将打印“func”的返回值。
然而,“shuffle”的返回类型为 None,因为列表将被就地修改,因此它不会打印任何内容。
解决方法:
如果您更喜欢函数式编程风格,您可能需要创建以下包装函数:
'print func(foo)' will print the return value of 'func' when called with 'foo'.
'shuffle' however has None as its return type, as the list will be modified in place, hence it prints nothing.
Workaround:
If you're more into functional programming style you might want to make the following wrapper function:
我们可以定义一个名为
shuffled
的函数(与sort
与sorted
的含义相同)One can define a function called
shuffled
(in the same sense ofsort
vssorted
)shuffle
已到位,因此不打印结果,即None
,而是打印列表。shuffle
is in place, so do not print result, which isNone
, but the list.您可以使用 shuffle 或 Sample 。 两者都来自 random 模块。
或者
you can either use shuffle or sample . both of which come from random module.
OR
如果您需要就地改组和操作种子的能力,此代码段将有所帮助:
请记住,“改组”是按随机键进行排序。
In case you need an in-place shuffling and ability to manipulate seed, this snippet would help:
Remember that "shuffling" is a sorting by randomised key.
确保您没有将源文件命名为 random.py,并且工作目录中没有名为 random.pyc 的文件。这两种情况都可能导致您的程序尝试导入本地 random.py 文件而不是 python 的 random 模块。
Make sure you are not naming your source file random.py, and that there is not a file in your working directory called random.pyc.. either could cause your program to try and import your local random.py file instead of pythons random module.
您可以这样做:
如果您想返回两个列表,则可以将这个长列表分成两个。
You can go for this:
if you want to go back to two lists, you then split this long list into two.
您可以构建一个函数,将列表作为参数并返回列表的打乱版本:
you could build a function that takes a list as a parameter and returns a shuffled version of the list:
对于任何有兴趣使用索引顺序方法的人 (Ouarda et.al., 1997< /a>) 重新排序列表:
这适用于单值列表...
这将打印出...
或嵌套列表的列表...
这将打印出...
@Shantanu Sharma 提供了一些很棒的方法,可以将值列表分解为一系列嵌套的值大小为 n 的列表。
这是我使用的方法...
这将打印出来...
For anyone interested in using the Index Sequential Method (Ouarda et.al., 1997) to reorder a list:
This will work for a single value list...
This will print out...
or a list of nested lists...
This will print out...
@Shantanu Sharma provides some great methods for breaking a list of values into a sequence of nested lists of size n.
Here's the method I used...
This will print out...
洗牌过程是“有替换”,因此每一项的出现次数都可能发生变化! 至少当列表中的项目也列出时。
例如,
之后,
[0]的数量可以是9或8,但不完全是10。
The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.
E.g.,
After,
The number of [0] may be 9 or 8, but not exactly 10.
计划:写出随机播放,而不依赖库来完成繁重的工作。 示例:从元素 0 开始遍历列表; 为其找到一个新的随机位置,例如 6,将 0 的值放入 6,将 6 的值放入 0。移至元素 1 并重复此过程,依此类推,直到列表的其余部分
Plan: Write out the shuffle without relying on a library to do the heavy lifting. Example: Go through the list from the beginning starting with element 0; find a new random position for it, say 6, put 0’s value in 6 and 6’s value in 0. Move on to element 1 and repeat this process, and so on through the rest of the list
您可以使用 random.choices() 来随机排列列表。
上面的代码将返回一个与之前的列表长度相同的随机列表。
You can use
random.choices()
to shuffle your list.The above code will return a randomized list same length as your previous list.
效果很好。 我在这里尝试使用函数作为列表对象:
它打印出来:
foo1 foo2 foo3
foo2 foo3 foo1
(最后一行的 foo 顺序随机)
It works fine. I am trying it here with functions as list objects:
It prints out:
foo1 foo2 foo3
foo2 foo3 foo1
(the foos in the last row have a random order)