I have a list of points with their coordinates, looking like this:
[(0,1),(2,3),(7,-1) and so on.]
What is the Pythonic way to iterate over them and choose three different every time? I can't find simpler solution than using three for
loops like this:
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'm asking for help.
import random
lst = [(0, 1), (2, 3), (7, -1), (1, 2), (4, 5)]
random.sample(lst, 3)
This will just give you 3 points chosen at random from the list. It seems you may want something different. Can you clarify?
You can use itertools.combinations
:
from itertools import combinations
for point1, point2, point3 in combinations(points, 3):
...
Use a set
.
Let's assume your initial set of coordinates is unique.
>> uniquechoices=[(0,1),(2,3),(7,-1) and so on.]
Fill a set called selected
until it has say 3 values, using random selection
>> from random import randint
>> selected=set([])
>> while len(selected) < 3: selected.add(uniquechoices[randomint(0,len(uniquechoices))])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.