首页 > 解决方案 > Python - 如何避免重复(列表)?

问题描述

import random
d = [0,0,0,0,0,0,0,0,0,0,0,0,0]
for i in range(1, 13):
    d[i] = random.randint(0,10)
    print(d)

for i in range(10):            
    perturbdp = random.randint(1,12)
    d[perturbdp] = random.randint(0,10)
    print(perturbdp)
    print(d)    

输出:

[0, 3, 5, 1, 2, 2, 10, 0, 8, 0, 4, 8, 8]
8
[0, 3, 5, 1, 2, 2, 10, 0, 7, 0, 4, 8, 8]
10
[0, 3, 5, 1, 2, 2, 10, 0, 7, 0, 9, 8, 8]
9
[0, 3, 5, 1, 2, 2, 10, 0, 7, 2, 9, 8, 8]
10
[0, 3, 5, 1, 2, 2, 10, 0, 7, 2, 6, 8, 8]
12
[0, 3, 5, 1, 2, 2, 10, 0, 7, 2, 6, 8, 8]
12
[0, 3, 5, 1, 2, 2, 10, 0, 7, 2, 6, 8, 2]
8
[0, 3, 5, 1, 2, 2, 10, 0, 8, 2, 6, 8, 2]
6
[0, 3, 5, 1, 2, 2, 1, 0, 8, 2, 6, 8, 2]
7
[0, 3, 5, 1, 2, 2, 1, 6, 8, 2, 6, 8, 2]
10
[0, 3, 5, 1, 2, 2, 1, 6, 8, 2, 6, 8, 2]

我根据代码创建了随机列表。

当我通过选择某个位置进行迭代以进一步生成时,它会选择并用相同的值替换该值。请查看输出部分的最后 3 行。它选择了位置 10,并再次替换为 6。我们怎样才能避免这种情况?

标签: python

解决方案


重复直到它与当前值不同:

for i in range(10):            
    perturbdp = random.randint(1,12)
    new_value = random.randint(0,10)
    while new_value == d[perturbdp]:
        new_value = random.randint(0,10)
    d[perturbdp] = new_value
    print(perturbdp)
    print(d)  

如果您不希望输出之间有任何重复,则需要遍历所有可能的组合:

from itertools import combinations_with_replacement
import random

comb = combinations_with_replacement(range(11), 13) # all 13-elements combinations of int between 0 and 10
comb_r = [*comb]        # putting them in a list
random.shuffle(comb_r)  # shuffling the list

number_of_outputs = 10
for i in range(number_of_outputs):
    print(list(comb_r[i]))

推荐阅读