iT邦幫忙

1

List join with extend vs. chain in python

在 python 中要將兩個 list 連接起來的方法有很多
以下主要比較用三種方法:
__add__, list.extenditertools.chain後轉list

import time
from itertools import chain

one = list(range(10000))
two = list(range(10000))

def use_add():
    three = one + two

def use_extend():
    three = one.copy()
    three.extend(two)

def use_chain():
    three = list(chain(one, two))

Add

start_time = time.time()
for _ in range(10000):
    use_add()
time.time() - start_time

Time: 0.9798197746276855 s

Extend

start_time = time.time()
for _ in range(10000):
    use_extend()
time.time() - start_time

Time: 0.9656569957733154 s

Chain

start_time = time.time()
for _ in range(10000):
    use_chain()
time.time() - start_time

Time: 2.501063823699951 s

__add__extend 幾乎一樣,到collections裡面找實做的方法,發現__add__基本上是直接呼叫extend,所以時間上自然幾乎一樣:

class MutableSequence(Sequence):
    pass
    
    def __iadd__(self, values):
        self.extend(values)
        return self

至於chain 比另外兩者慢了快2.5倍,原因可能是 chain 完後是生成迭代器,透過list將迭代器再轉換成list的時候需要在對每個元素檢查一次,所以用了更多時間。


不知道這樣的測試是否正確,希望大家可以多給我些意見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
一級屠豬士
iT邦大師 1 級 ‧ 2020-01-10 10:06:21

還有最基本的方式,你沒測喔.

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
highwall iT邦新手 5 級 ‧ 2020-01-10 10:57:46 檢舉

謝謝補充

我要留言

立即登入留言