Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip two differently sized lists?

I want to zip two list with different length

for example

A = [1,2,3,4,5,6,7,8,9] B = ["A","B","C"] 

and I expect this

[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'A'), (5, 'B'), (6, 'C'), (7, 'A'), (8, 'B'), (9, 'C')] 

But the build-in zip won't repeat to pair with the list with larger size . Does there exist any build-in way can achieve this? thanks

here is my code

idx = 0 zip_list = [] for value in larger:     zip_list.append((value,smaller[idx]))     idx += 1     if idx == len(smaller):         idx = 0 
like image 954
user2131116 Avatar asked Oct 30 '13 15:10

user2131116


People also ask

Can you zip two lists of different lengths?

The zip() function will only iterate over the smallest list passed. If given lists of different lengths, the resulting combination will only be as long as the smallest list passed.

How do you zip multiple lists in Python?

To zip multiple lists, you can just do zip(list1, list2, list3) , etc.

Can I zip 3 lists Python?

Python zip three listsPython zipping of three lists by using the zip() function with as many inputs iterables required. The length of the resulting tuples will always equal the number of iterables you pass as arguments. This is how we can zip three lists in Python.


2 Answers

You can use itertools.cycle:

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.

Example:

A = [1,2,3,4,5,6,7,8,9] B = ["A","B","C"]  from itertools import cycle zip_list = zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B) 
like image 115
sloth Avatar answered Sep 20 '22 08:09

sloth


Try this.

A = [1,2,3,4,5,6,7,8,9] B = ["A","B","C"] Z = [] for i, a in enumerate(A):     Z.append((a, B[i % len(B)])) 

Just make sure that the larger list is in A.

like image 33
Eser Aygün Avatar answered Sep 21 '22 08:09

Eser Aygün