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