Unpack tuple in list comprehension
Ngày đăng:
28/12/2021
Trả lời:
0
Lượt xem:
96
Python list comprehension, unpacking and multiple operationsUse a nested list comprehension: Example: This will work fine for your more general case as well, or you could do it all in one step: y = [a for i in x for a in (i, sqrt(i), i**3, some_operation_on_i, f(i), g(i))]In case the nested list comprehensions look odd, here is how this would look as a normal for loop: y = [] for i in x: for a in (i, sqrt(i), i**3, some_operation_on_i, f(i), g(i)): y.append(a)>>> import itertools >>> list(itertools.chain.from_iterable(y)) [0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81] |