Home > front end >  Extracting values from zipped list and tuple at the same time
Extracting values from zipped list and tuple at the same time

Time:12-06

I have a list of tuple and a list of scalar value and I want to extract values from them at the same time. e.g.

>>> a = [('type1', 1), ('type2', 2)]
>>> b = [res1, res2]
>>> for ai, bi in zip(a, b):
...     ai1, ai2 = ai
...     print(ai1, ai2, bi)
...
type1 1 res1
type2 2 res2

How can we avoid step of re splitting ai in loop itself.

# something like this (This does not work though)
>>> for ai1, ai2, bi in zip(a, b):
...     ai1, ai2 = ai
...     print(ai1, ai2, bi)

CodePudding user response:

Just add the appropriate parentheses:

>>> a = [('type1', 1), ('type2', 2)]
>>> b = ["FOO", "BAR"]
>>> for (ai1, ai2), bi in zip(a, b):
...     print(ai1, ai2, bi)
...
type1 1 FOO
type2 2 BAR

Note, for iterable unpacking, square brackets and parentheses work the same:

>>> for [ai1, ai2], bi in zip(a, b):
...     print(ai1, ai2, bi)
...
type1 1 FOO
type2 2 BAR

CodePudding user response:

You can use brackets to achieve exactly that.

for (ai1, ai2), bi in zip(a, b):
    print(ai1, ai2, bi)
  • Related