Skip to content Skip to sidebar Skip to footer

Combine A List With A List Of Varied Length Within A List

I am trying to combine historical data, which comes from an ancient custom made email system, to create a database with Python. One list (b) contains the email id, and another list

Solution 1:

I hope I've understood your question right (in your output you have c4 but I think it should be c3):

a = [[], ["a"], ["b", "c", "d"]]
b = ["c1", "c2", "c3"]

out = [[[v, s] for s in l] for v, l in [t for t inzip(b, a) if t[1]]]
print(out)

Prints:

[[["c2", "a"]], [["c3", "b"], ["c3", "c"], ["c3", "d"]]]

Solution 2:

With meaningful names (and without Andrej's inexplicable extra comprehension ;-):

attachment_lists = [[], ['a'], ['b', 'c', 'd']]
emails = ['c1', 'c2', 'c3']

result = [[[email, attachment] for attachment in attachments]
          for email, attachments inzip(emails, attachment_lists)
          if attachments]

print(result)

Output (Try it online!):

[[['c2', 'a']], [['c3', 'b'], ['c3', 'c'], ['c3', 'd']]]

Post a Comment for "Combine A List With A List Of Varied Length Within A List"