Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose three different values from list in Python

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.

like image 727
Dmitry Avatar asked Jan 08 '16 18:01

Dmitry


People also ask

How do you select multiple values from a list in Python?

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).

How do you select a specific item in a list Python?

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.

How do you find the intersection of three lists in Python?

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.


3 Answers

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?

like image 99
jgritty Avatar answered Sep 22 '22 00:09

jgritty


You can use itertools.combinations:

from itertools import combinations

for point1, point2, point3 in combinations(points, 3):
    ...
like image 44
Delgan Avatar answered Sep 19 '22 00:09

Delgan


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))])
like image 38
user5155 Avatar answered Sep 20 '22 00:09

user5155