python - 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。我们怎样才能避免这种情况?
解决方案
重复直到它与当前值不同:
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]))
推荐阅读
- xmonad - 如何将当前工作区而不是当前窗口发送到不同的屏幕?
- php - 如何防止 SQL 舍入 PHP 输入值
- amazon-ec2 - 无法将文件从本地生产服务器传输到 PLE 服务器中的 AWS EC2
- mysql - 如何构建 SQL 查询以生成 3 维矩阵?
- django - 如何使用 rest_framework 序列化程序获取链接到给定外部 ket 字段的所有对象?
- intellij-idea - IntelliJ IDEA 2018.3 将“撤消”/“重做”等添加到工具栏
- java - Servlet 无法向jsp输出HashMap键:FileNotFoundException, util class can't find local file after deploy
- php - 如何从 php 循环中自动生成 Schema.org Google 丰富片段
- visual-studio-code - git_bash 代码命令在 VS 代码中不起作用
- ios - 将图像从设备上传到 Firebase