提问人:Manisha Biswas 提问时间:10/23/2019 更新时间:10/23/2019 访问量:407
如何从python列表中删除随机生成的重复值
How to remove duplicate values generated randomly from list in python
问:
我有一个输入点列表:
input_points = [{'name': 'a', 'value': (0.0, 1.0)}, {'name': 'b', 'value': (2.0, 1.0)},
{'name': 'c', 'value': (3.0, 1.0)}, {'name': 'd', 'value': (0.0, 3.0)},
{'name': 'e', 'value': (1.0, 2.0)}, {'name': 'f', 'value': (1.5, 1.5)},
{'name': 'g', 'value': (1.0, 1.0)}, {'name': 'h', 'value': (1.5, 2.0)}]
我必须迭代生成两个随机点。我使用 random.sample() 作为:
for x in range(100):
point1 = random.sample(input_points, 2)
print(point1)
但它给了我一个重复点的组合,这就是为什么我没有一直得到 100 次迭代列表中所有点的组合。但是我只需要在 100 次迭代中遍历所有点。有什么方法可以删除重复项,从而在 100 次迭代中获得所有点的组合。
谢谢
答:
0赞
Selcuk
10/23/2019
#1
您可以使用嵌套循环以迭代方式找到所有迭代:
pairs = []
for i, point1 in enumerate(input_points):
for point2 in input_points[i+1:]:
pairs.append([point1, point2])
然而,Ransac 算法取决于随机样本以及它们与模型的拟合程度。
0赞
DarrylG
10/23/2019
#2
我们可以:
1)创建所有点组合对。
2)对这些对进行随机抽样。
import random
from itertools import combinations
input_points = [{'name': 'a', 'value': (0.0, 1.0)}, {'name': 'b', 'value': (2.0, 1.0)},
{'name': 'c', 'value': (3.0, 1.0)}, {'name': 'd', 'value': (0.0, 3.0)},
{'name': 'e', 'value': (1.0, 2.0)}, {'name': 'f', 'value': (1.5, 1.5)},
{'name': 'g', 'value': (1.0, 1.0)}, {'name': 'h', 'value': (1.5, 2.0)}]
all_pairs = list(combinations(input_points, 2))
y = random.sample(all_pairs, 10) # random sample of pairs
# (in this case 10 pairs)
# max we could get is 28
评论
random
random
for