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.
You can also pick multiple items in a list. In this example, we call on our variable, list1, and the items zero through two. Python pulls the first and second items only. The brackets' semicolon tells python to pull items in the list from the first noted number (zero) to the last number but exempt it(three).
To select elements from a Python list, we will use list. append(). We will create a list of indices to be accessed and the loop is used to iterate through this index list to access the specified element. And then we add these elements to the new list using an index.
Step1: input the elements of three lists. Step2: Use intersection method, first convert lists to sets then apply intersection method of two sets and find out common elements then this set intersect with the third set.
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))])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With