Leg*_*ess 2 python list python-2.7
我有以下列表:
a = [1, 2, 5, 4, 3, 6]
Run Code Online (Sandbox Code Playgroud)
而且我想知道如何在列表中随机交换任意两个值,而不管列表中的位置如何.以下是我正在考虑的一些示例输出:
[1, 4, 5, 2, 3, 6]
[6, 2, 3, 4, 5, 1]
[1, 6, 5, 4, 3, 2]
[1, 3, 5, 4, 2, 6]
Run Code Online (Sandbox Code Playgroud)
有没有办法在Python 2.7中执行此操作?我目前的代码是这样的:
import random
n = len(a)
if n:
i = random.randint(0,n-1)
j = random.randint(0,n-1)
a[i] += a[j]
a[j] = a[i] - a[j]
a[i] -= a[j]
Run Code Online (Sandbox Code Playgroud)
然而,我目前拥有的代码的问题是,如果给出足够的交换和迭代,它会开始将所有值设置为零,这是我不想要的; 我希望值在数组中保持不变,但是执行类似于2opt的操作,并且每次交换时只切换两次.
看来,你过于复杂了.只需从列表中随机抽取两个索引,然后交换这些指标的值:
>>> def swap_random(seq):
... idx = range(len(seq))
... i1, i2 = random.sample(idx, 2)
... seq[i1], seq[i2] = seq[i2], seq[i1]
...
>>> a
[1, 2, 5, 4, 3, 6]
>>> swap_random(a)
>>> a
[1, 2, 3, 4, 5, 6]
>>> swap_random(a)
>>> a
[1, 2, 6, 4, 5, 3]
>>> swap_random(a)
>>> a
[1, 2, 6, 5, 4, 3]
>>> swap_random(a)
>>> a
[6, 2, 1, 5, 4, 3]
Run Code Online (Sandbox Code Playgroud)
注意,我使用了Python交换习语,它不需要中间变量.它相当于:
temp = seq[i1]
seq[i1] = seq[i2]
seq[i2] = temp
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2391 次 |
| 最近记录: |