Comprehensions in Python to sample tuples from a list -
i trying list of three-element tuples list [-4, -2, 1, 2, 5, 0] using comprehensions, , checking whether fulfil condition sum([] == 0). following code works. however, there no question there ought easier, more elegant way of expressing these comprehensions:
[ (i, j, k) in [-4, -2, 1, 2, 5, 0] j in [-4, -2, 1, 2, 5, 0] 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 searching expression (i, j, k) i, j, k in [-4, -2, 1, 2, 5, 0].
you can use itertools.product hide nested loops in list comprehension. use repeat parameter set number of loops on list (i.e. number of elements in tuple):
>>> import itertools >>> lst = [-4, -2, 1, 2, 5, 0] >>> [x 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)]
Comments
Post a Comment