Select three different values ​​from a list in Python

I have a list of points with their coordinates, which looks like this:

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

What is Pythonic to iterate over and select three different each time? I cannot find a simpler solution than using three for loops, such as:

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

So, I ask for help.

+6
source share
3 answers

You can use itertools.combinations :

 from itertools import combinations for point1, point2, point3 in combinations(points, 3): ... 
+6
source
 import random lst = [(0, 1), (2, 3), (7, -1), (1, 2), (4, 5)] random.sample(lst, 3) 

This will just give you 3 points randomly selected from the list. It seems you might need something else. Can you clarify?

+7
source

Use set .

Suppose your original coordinate set is unique.

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

Fill the set named selected until it says 3 values ​​using random selection

 >> from random import randint >> selected=set([]) >> while len(selected) < 3: selected.add(uniquechoices[randomint(0,len(uniquechoices))]) 
+2
source

All Articles