How do I merge two lists into a single list?
我有
1 2 | a = [1, 2] b = ['a', 'b'] |
我想要
1 | c = [1, 'a', 2, 'b'] |
号
1 | [j for i in zip(a,b) for j in i] |
。
如果元素的顺序与示例中的顺序非常匹配,则可以使用zip和chain的组合:
1 2 | from itertools import chain c = list(chain(*zip(a,b))) |
如果您不关心结果中元素的顺序,那么有一种更简单的方法:
1 | c = a + b |
号
正在分析
1 | [j for i in zip(a,b) for j in i] |
。
如果你记得
1 2 3 4 | temp = [] for i in zip(a, b): for j in i: temp.append(j) |
。
如果它是用更有意义的变量名来写的话会更容易些:
1 | [item for pair in zip(a, b) for item in pair] |
。
另一种方法是使用索引切片,结果发现它比Zip更快,扩展性更好:
1 2 3 4 5 | def slicezip(a, b): result = [0]*(len(a)+len(b)) result[::2] = a result[1::2] = b return result |
您会注意到,这只在
进行比较:
1 2 3 4 5 6 7 8 9 10 11 | 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 |
。
如果您关心订单:
1 2 3 4 5 6 | #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. |
这里有一个标准/自我解释的解决方案,我希望有人会发现它有用:
1 2 3 4 5 6 7 8 9 | a = ['a', 'b', 'c'] b = ['1', '2', '3'] c = [] for x, y in zip(a, b): c.append(x) c.append(y) print (c) |
号
输出:
1 | ['a', '1', 'b', '2', 'c', '3'] |
号
当然,如果需要,您可以更改它并对值进行操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 |
主体()
1 2 3 | c = [] c.extend(a) c.extend(b) |
。