Home > front end >  Concatenation of elements in type zip in Python
Concatenation of elements in type zip in Python

Time:10-19

In Python, I received a type zip like this as input:

[
    ('ef', ['c', 'b', 'a']),
    ('a', ['b']),
    ('ab', ['c']),
    ('b', ['c']),
    ('c', ['c', 'a']),
]

I have to concatenate the elements in the same item and create a new list of strings. The expected output is:

['efc', 'efb', 'efa', 'ab', 'abc', 'bc', 'cc', 'ca']

Note that the first element generates three different strings and the last one generates two strings. The problem is these items, because it has more than one element to concatenate. I tried using the join command but it is not working. Any help would be appreciated.

CodePudding user response:

Use a nested comprehension:

>>> zipped = [
    ('ef', ['c', 'b', 'a']),
    ('a', ['b']),
    ('ab', ['c']),
    ('b', ['c']),
    ('c', ['c', 'a']),
]
>>> [pre   s for pre, suf in zipped for s in suf]
['efc', 'efb', 'efa', 'ab', 'abc', 'bc', 'cc', 'ca']

If the comprehension doesn't make sense on first glance, think about it like a nested for loop:

>>> for pre, suf in zipped:
...     for s in suf:
...         print(pre   s)
... 
efc
efb
efa
ab
abc
bc
cc
ca

CodePudding user response:

You could use itertools.chain and itertools.product along with str.join for this:

data = [('ef', ['c', 'b', 'a']), ('a', ['b']), ('ab', ['c']), ('b', ['c']), ('c', ['c', 'a'])]

list(chain.from_iterable(map(''.join, product([s], li)) for s, li in data))

['efc', 'efb', 'efa', 'ab', 'abc', 'bc', 'cc', 'ca']
  • Related