我有两个清单:
a = ['a', 'b', 'c', 'd']
b = ['e', 'f', 'g', 'h']
我想合并到一个包含元素nr的列表。列表a中的第1个作为第一个元素,列表b的元素nr.1作为第二个元素,元素nr。列表中的2列为第三个元素,依此类推,如下所示:
c = ['a', 'e', 'b', 'f', 'c', 'g', 'd', 'h']
最简单的方法是什么,可能不使用循环?
答案 0 :(得分:6)
将zip
成对,然后使用itertools.chain.from_iterable
平整列表:
In [1]: a=['a','b','c','d']
In [2]: b=['e','f','g','h']
In [3]: from itertools import chain
In [4]: chain.from_iterable(zip(a, b))
Out[4]: <itertools.chain at 0x7fbcf2335ef0>
In [5]: list(chain.from_iterable(zip(a, b)))
Out[5]: ['a', 'e', 'b', 'f', 'c', 'g', 'd', 'h']
答案 1 :(得分:2)
这是一个答案,比较一些可能的方法与2个不同的数据集,一个将包含许多小数组,另一个将是几个大数组:
导入时间 随机导入 来自itertools导入链
def f1(a, b):
return list(chain.from_iterable(zip(a, b)))
def f2(a, b):
return list(sum(zip(a, b), ()))
def f3(a, b):
result = []
for (e1, e2) in zip(a, b):
result += [e1, e2]
return result
def f4(a, b):
result = []
len_result = min(len(a), len(b))
result = []
i = 0
while i < len_result:
result.append(a[i])
result.append(b[i])
i += 1
return result
# Small benchmark
N = 5000000
a_small = ['a', 'b', 'c', 'd']
b_small = ['e', 'f', 'g', 'h']
benchmark1 = [
timeit.timeit(
'f1(a_small, b_small)', setup='from __main__ import f1, a_small,b_small', number=N),
timeit.timeit(
'f2(a_small, b_small)', setup='from __main__ import f2, a_small,b_small', number=N),
timeit.timeit(
'f3(a_small, b_small)', setup='from __main__ import f3, a_small,b_small', number=N),
timeit.timeit(
'f4(a_small, b_small)', setup='from __main__ import f4, a_small,b_small', number=N)
]
for index, value in enumerate(benchmark1):
print " - Small sample with {0} elements -> f{1}={2}".format(len(a_small), index + 1, value)
# Large benchmark
N = 5000
K = 100000
P = 1000
a_large = random.sample(range(K), P)
b_large = random.sample(range(K), P)
benchmark2 = [
timeit.timeit(
'f1(a_large, b_large)', setup='from __main__ import f1, a_large,b_large', number=N),
timeit.timeit(
'f2(a_large, b_large)', setup='from __main__ import f2, a_large,b_large', number=N),
timeit.timeit(
'f3(a_large, b_large)', setup='from __main__ import f3, a_large,b_large', number=N),
timeit.timeit(
'f4(a_large, b_large)', setup='from __main__ import f4, a_large,b_large', number=N)
]
for index, value in enumerate(benchmark2):
print " - Large sample with {0} elements -> f{1}={2}".format(K, index + 1, value)
结论:当N很大且列表很小时,似乎f2函数是稍快的方法。当数组很大且数量很少时,f1就是赢家。
规格:Python2.7.11(64),在i-7 2.6Ghz上N = 5000000