thecooldudes12345
thecooldudes12345

Reputation: 13

Adding an element to two elements in a list at a time

Not too sure how to build this, but I am trying to add one element from one list to another.

x = [1,1,2,2,3,3]

a=[['b'],['c'],['d'],['e'],['f'],['g'],['h'],['i'],['j'],['k'],['l'],['m']]

And I'm trying to get an output like this where it adds one element:

a=[['b',1],['c',1],['d',2],['e',2],['f',3],['g',3],['h',1],['i',1],['j',2],['k',2],['l',3],['m',3]]

Upvotes: 1

Views: 64

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477854

If you want to modify the lists, you can use a for loop and use itertools.cycle:

from itertools import cycle

for ai,xi in zip(a,cycle(x)):
    ai.append(xi)

which gives:

>>> a
[['b', 1], ['c', 1], ['d', 2], ['e', 2], ['f', 3], ['g', 3], ['h', 1], ['i', 1], ['j', 2], ['k', 2], ['l', 3], ['m', 3]]

If you do not care about the original lists, you can also use list comprehension to construct a new list of lists:

a[:] = [ai+[xi] for ai,xi in zip(a,cycle(x))]

which gives:

>>> [ai+[xi] for ai,xi in zip(a,cycle(x))]
[['b', 1], ['c', 1], ['d', 2], ['e', 2], ['f', 3], ['g', 3], ['h', 1], ['i', 1], ['j', 2], ['k', 2], ['l', 3], ['m', 3]]

Upvotes: 4

Neil
Neil

Reputation: 14321

This can be accomplished in native Python by using the mod operator:

x = [1,1,2,2,3,3]
a=[['b'],['c'],['d'],['e'],['f'],['g'],['h'],['i'],['j'],['k'],['l'],['m']]
results = [[value[0], x[index % len(x)]] for index, value in enumerate(a)]
print(results)

Upvotes: 4

Related Questions