从Python中的列表中选择三个不同的值

时间:2016-01-08 18:08:45

标签: python algorithm python-3.x

我有一个带坐标的点列表,如下所示:

[(0,1),(2,3),(7,-1) and so on.]

什么是Pythonic迭代它们并每次选择三种不同的方法?我找不到比使用三个for循环更简单的解决方案:

for point1 in a:
    for point2 in a:
        if not point1 == point2:
        for point3 in a:
            if not point1 == point3 and not point2 == point3:

所以我要求帮助。

3 个答案:

答案 0 :(得分:7)

import random

lst = [(0, 1), (2, 3), (7, -1), (1, 2), (4, 5)]

random.sample(lst, 3)

这只会从列表中随机选择3分。看来你可能想要一些不同的东西。你能说清楚吗?

答案 1 :(得分:6)

您可以使用itertools.combinations

from itertools import combinations

for point1, point2, point3 in combinations(points, 3):
    ...

答案 2 :(得分:2)

使用set

假设您的初始坐标集是唯一的。

>> uniquechoices=[(0,1),(2,3),(7,-1) and so on.]

使用随机选择

填充一个名为selected的集合,直到它说出3个值
>> from random import randint
>> selected=set([])
>> while len(selected) < 3: selected.add(uniquechoices[randomint(0,len(uniquechoices))])