我有兩個列表:合併兩個列表的
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']
什麼是這樣做的,可能不使用循環的最簡單的方法?
我有兩個列表:合併兩個列表的
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']
什麼是這樣做的,可能不使用循環的最簡單的方法?
只是其中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']
這裏是比較一些與2型動物的數據集可能的方法的答案,一會由許多小陣列,其他人會是一些大型陣列:從itertools進口環鏈
進口timeit 進口隨機
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)
結論:似乎F2功能是稍快方法時,N是大和列表是豆蔻。當數組很大並且數目很少時,雖然f1是勝利者。
規格:Python2.7.11(64),N上的i-7 2.6GHz的= 5000000
因爲問題已經關閉,我就不能發佈我的基準,但最快的答案到目前爲止,這是' list(sum(zip(a,b),()))' – BPL
@BPL期待您的基準,請求重新提出 – soon
@soon謝謝!有時管理員應該多給一點時間,即使他們是重複的問題...你總能找到一些人發佈新的有趣數據爲問題增加價值;) – BPL