繁体   English   中英

随机移动Python列表中的一定数量的项目

[英]Randomly move a certain number of items in a Python list

所以我一直在做一些排序算法,我想运行一个测试函数,生成不同类型的列表来运行我的排序算法。

一个这样的列表将是已经排序的列表,其中列表中的n个项目随机地被洗牌(但不是全部,列表仍然应该被排序而不是n个项目)

testlist = random.sample(range(0,10),10)
testlist.sort()

这给了我一个大小为10的独特项目的排序列表,但后来我不确定如何将列表中的这10个项目中的n个移动到随机位置,只是为了混合排序

这是在列表中随机播放一些项目的一种方法:

import random
import numpy as np

# Make a sorted list of integers.
x = np.array(range(100))

# Choose 10 indices at random.
r = random.sample(range(len(x)), 10)

# Copy this list and shuffle.
s = r.copy()
random.shuffle(s)

# Replace the indices with the shuffled ones.
x[r] = x[s]

请注意,这可能会保留一些索引不变

这是一个受控的实现。 随机选择四个指数以进行切换。 将这些值洗牌,然后将它们放回四个指定的位置。 请注意,它不保证新值将全部不同。

import random
import copy

testlist = random.sample(range(0, 20), 10)
testlist.sort()
print testlist

n = 4
move_set = set()
while len(move_set) < n:
    move_set.add(random.randrange(0, 10))

print move_set
move_list = list(move_set)

# Replace n elements
test1 = copy.copy(testlist)
migrant = [test1[_] for _ in move_set]
random.shuffle(migrant)
print migrant
test_case = []
for i in range(n):
    test1[move_list[i]] = migrant[i]
print test1

输出:

[0, 3, 4, 5, 7, 8, 9, 12, 16, 17]
set([9, 3, 4, 5])
[5, 17, 8, 7]
[0, 3, 4, 17, 8, 7, 9, 12, 16, 5]

在这次运行中,所有四个指数都是列表中的值也是巧合。 元件9,3,4和5分别具有值17,1,5和8。 洗牌将四者中的每一个都放入新的位置。

像这样的东西会起作用。 基本上,只需随机选择两个索引并切换它们,而不是多次切换相同的索引。 如果在已排序的数组上运行,它确实确保正好n元素未排序。 仅适用于偶数替换。

array = list(range(10))

def shuffle_n(array, n):
    assert n <= len(array) and n % 2 == 0
    indexes = set(range(len(array)))
    for i in range(n // 2):
        a, b = random.sample(indexes, 2)
        indexes.remove(a)
        indexes.remove(b)
        array[a], array[b] = array[b], array[a]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM