Visualisation App
Visualisation App

Reputation: 798

How to zip unequal lists as a product of first list with others?

I have multiple lists like following-

list1=['Tom']
list2=[16]
list3=['Maths','Science','English']
list4=['A','B','C']

I want to zip these lists to achieve the following mapping-

desired results-

[('Tom', 16, 'Maths','A'), ('Tom', 16, 'Science','B'), ('Tom', 16, 'English','C')]

Result i am getting by using the following command-

results=zip(list1,list2,list3,list4)
[('Tom', 16, 'Maths','A')]

this is just an example of my problem.If a generalised solution is provided it would be helpful. If I use the statement-

res= itertools.izip_longest(*[x[c] for c in cols])

I am getting multiple rows but getting null for the name and age column. Also consider passing the column names in the above way since the names of columns are not static.

Upvotes: 1

Views: 361

Answers (2)

jpp
jpp

Reputation: 164793

You are not looking to zip 4 lists here since, as you have confirmed, the first 2 lists only ever contain one item.

Instead, use a list comprehension and zip just the final 2 lists:

name, age = list1[0], list2[0]
res = [(name, age, subject, grade) for subject, grade in zip(list3, list4)]

print(res)

[('Tom', 16, 'Maths', 'A'),
 ('Tom', 16, 'Science', 'B'),
 ('Tom', 16, 'English', 'C')]

Upvotes: 2

user9145571
user9145571

Reputation:

I assume here that list4 is the list the one with the most elements.

list1 = ['Tom']
list2 = [16]
list3 = ['Maths', 'Science', 'English']
list4 = ['A', 'B', 'C']
longest = (list4 if (len(list4) > len(list3)) else list3)
shortest = (list3 if (longest == list4) else list4)

for list_ in (list1, list2, shortest):
    while len(list_) < len(longest):
        list_.append(list_[-1])

zip_list = zip(list1, list2, shortest, longest)

Upvotes: 1

Related Questions