Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comprehensions in Python to sample tuples from a list

I am trying to get the list of three-element tuples from the list [-4, -2, 1, 2, 5, 0] using comprehensions, and checking whether they fulfil the condition sum([] == 0). The following code works. However, there is no question that there ought to be an easier, much more elegant way of expressing these comprehensions:

[
    (i, j, k) for i in [-4, -2, 1, 2, 5, 0]
              for j in [-4, -2, 1, 2, 5, 0]
              for k in [-4, -2, 1, 2, 5, 0] if sum([i, j, k]) == 0
]

Output:

[(-4, 2, 2), (-2, 1, 1), (-2, 2, 0), (-2, 0, 2), (1, -2, 1), 
 (1, 1, -2), (2, -4, 2), (2, -2, 0), (2, 2, -4), (2, 0, -2), 
 (0, -2, 2), (0, 2, -2), (0, 0, 0)]

The question is searching for an expression like (i, j, k) for i, j, k in [-4, -2, 1, 2, 5, 0].

like image 429
Antoni Parellada Avatar asked Jan 16 '16 20:01

Antoni Parellada


People also ask

How do I extract a tuple from a list in Python?

To extract the n-th elements from a list of tuples with Python, we can use list comprehension. We get the n-th element from each tuple and put them into a list with [x[n] for x in elements] . x is the tuple being retrieved. Therefore, e is [1, 3, 5] .

Can you do tuple comprehensions?

There is no tuple comprehension in Python. Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.

How do you do tuple comprehension in Python?

There is no tuple comprehension in Python, but you can get the desired result by using a generator expression and converting the generator object to a tuple, e.g. my_tuple = tuple(int(element) for element in ('1', '3', '5')) .


1 Answers

You can use itertools.product to hide the nested loops in your list comprehension. Use the repeat parameter to set the number of loops over the list (i.e. the number of elements in the tuple):

>>> import itertools
>>> lst = [-4, -2, 1, 2, 5, 0]
>>> [x for x in itertools.product(lst, repeat=3) if sum(x) == 0]
[(-4, 2, 2),
 (-2, 1, 1),
 (-2, 2, 0),
 (-2, 0, 2),
 (1, -2, 1),
 (1, 1, -2),
 (2, -4, 2),
 (2, -2, 0),
 (2, 2, -4),
 (2, 0, -2),
 (0, -2, 2),
 (0, 2, -2),
 (0, 0, 0)]
like image 91
Alex Riley Avatar answered Oct 19 '22 13:10

Alex Riley