Reputation: 4412
I have
a = [1, 2]
b = ['a', 'b']
I want
c = [1, 'a', 2, 'b']
Upvotes: 44
Views: 57360
Reputation: 129
Simple.. please follow this pattern.
x = [1 , 2 , 3]
y = ["a" , "b" , "c"]
z =list(zip(x,y))
print(z)
Upvotes: 3
Reputation: 82924
Parsing
[item for pair in zip(a, b) for item in pair]
in your head is easy enough if you recall that the for
and if
clauses are done in order, followed a final append of the result:
temp = []
for pair in zip(a, b):
for item in pair :
temp.append(item )
Upvotes: 23
Reputation: 1408
Here is a standard / self-explaining solution, i hope someone will find it useful:
a = ['a', 'b', 'c']
b = ['1', '2', '3']
c = []
for x, y in zip(a, b):
c.append(x)
c.append(y)
print (c)
output:
['a', '1', 'b', '2', 'c', '3']
Of course, you can change it and do manipulations on the values if needed
Upvotes: 0
Reputation: 1
def main():
drinks = ["Johnnie Walker", "Jose Cuervo", "Jim Beam", "Jack Daniels,"]
booze = [1, 2, 3, 4, 5]
num_drinks = []
x = 0
for i in booze:
if x < len(drinks):
num_drinks.append(drinks[x])
num_drinks.append(booze[x])
x += 1
else:
print(num_drinks)
return
main()
Upvotes: 0
Reputation: 51
An alternate method using index slicing which turns out to be faster and scales better than zip:
def slicezip(a, b):
result = [0]*(len(a)+len(b))
result[::2] = a
result[1::2] = b
return result
You'll notice that this only works if len(a) == len(b)
but putting conditions to emulate zip will not scale with a or b.
For comparison:
a = range(100)
b = range(100)
%timeit [j for i in zip(a,b) for j in i]
100000 loops, best of 3: 15.4 µs per loop
%timeit list(chain(*zip(a,b)))
100000 loops, best of 3: 11.9 µs per loop
%timeit slicezip(a,b)
100000 loops, best of 3: 2.76 µs per loop
Upvotes: 5
Reputation: 26717
If you care about order:
#import operator
import itertools
a = [1,2]
b = ['a','b']
#c = list(reduce(operator.add,zip(a,b))) # slow.
c = list(itertools.chain.from_iterable(zip(a,b))) # better.
print c
gives [1, 'a', 2, 'b']
Upvotes: 4
Reputation: 838096
If the order of the elements much match the order in your example then you can use a combination of zip and chain:
from itertools import chain
c = list(chain(*zip(a,b)))
If you don't care about the order of the elements in your result then there's a simpler way:
c = a + b
Upvotes: 30