打乱列表
在这个程序中,我试图通过从列表中随机选择两个项目并交换它们来打乱列表,然后重复此过程几次。
我遇到的问题是我不知道如何交换项目并打印打乱的列表。
例如,如果我的两个随机值是 a 和 b,如果我只是输入:
a = b
b = a
那么就会将 a 的值更改为 b,但是当它尝试将 b 更改为 a 时,不会发生任何更改,因为 a 已经更改至 b.
我认为这可行的唯一方法是同时交换它们,但我不知道交换它们的函数/方法。
另外,如果 a,b 是列表 L 的项目,在我交换它们之后,如果我使用它,
print L
它应该打印更改后的版本吗?我只是问,因为根据我的尝试,它并没有这样做。
注意,我试图通过交换来逐步洗牌此列表,而不是使用从随机导入的洗牌函数。
in this program I'm trying to shuffle a list by randomly choosing two items from a list and swapping them round, and then repeating this process several times.
The problem I have encountered is I don't know how I can swap the items round and print the shuffled list.
For instance if my two random values were a and b, if I were to just put:
a = b
b = a
then that would change the value of a to b, but when it tries to change b to a, no change would occur as a has already been changed to b.
The only way I can think that this would work is swapping them at the same time, but I do not know of a function/ way to swap them round.
Also if a, b were items of a list L, after I swapped them round if I used
print L
should it print the altered version? I only ask because from what I have tried it is not doing that.
NB I am trying to shuffle this list stage by stage by swapping, instead of using the shuffle function imported from random.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在Python中,你可以像这样交换两个变量:
这称为多重赋值,你可以找到更多关于它的信息这里。
在其他语言中,这通常是通过分配临时变量来完成的:
Python 不是很棒吗?
In Python, you can swap two variables like this:
This is called multiple assignment, you can find more information about it here.
In other languages this is usually done by assigning a temporary variable:
Isn't Python great?
random.shuffle 函数也使用交换。值得查看其源代码:
观察最后一行如何使用元组打包和解包执行交换。
作为打包和解包的替代方法,交换变量的传统方法是使用临时变量:
The random.shuffle function uses swapping too. It would be worthwhile to look at its source code:
Observe how the last line performs a swap using tuple packing and unpacking.
As an alternative to packing and unpacking, the traditional way to swap variables is to use a temporary variable:
使用临时变量来解决你的第一个问题:
在Python中你也可以这样做:
我怀疑你的第二个问题是因为你正在改变你从列表中得到的东西,而不是改变列表。试试这个:
Use a temp variable for your first problem:
In Python you can also do this:
I suspect your second problem is because you're changing things you got out of the list, instead of changing the list. Try this:
使用临时变量:
Use a temporary variable:
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle众所周知
,仅仅交换物品是不好的。
不要忘记,如果您有 n 个项目,那么就有 n 个!安排。如果你的随机数是32位,那么就有2^32个数字。
那么将一副 32 位数字洗成 52 就很难了!比 2^32 大很多
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Just swapping items is known to be bad.
Don't forget that if you have n items, there are n! arrangements. If your random number is 32 bits, there are 2^32 numbers.
It's hard then to shuffle a pack of cards with a 32 bit number as 52! is very much bigger than 2^32