>>> from random import choice
>>> from string import ascii_letters
>>> from timeit import Timer
>>> testdata = [(choice(ascii_letters), choice(ascii_letters)) for _ in range(10000)]
>>> count, total = Timer('[f"{s1}{s2}" for s1, s2 in mylist]', 'from __main__ import testdata as mylist').autorange()
>>> print(f"List comp with f-string, 10k elements: {total / count * 1000000:7.2f} microseconds")
List comp with f-string, 10k elements: 1249.37 microseconds
>>> count, total = Timer('[s1 + s2 for s1, s2 in mylist]', 'from __main__ import testdata as mylist').autorange()
>>> print(f"List comp with concatenation, 10k elements: {total / count * 1000000:6.2f} microseconds")
List comp with concatenation, 10k elements: 1061.89 microseconds
使用列表理解,对于两个元素,我将使用元组解压和连接:
另一个选择是使用formatted string literal:
^{pr2}$两者都相当快:
串联在这里获胜。在
列表理解消除了每次在循环中查找列表对象及其
.append()
方法的需要,请参见What is the advantage of a list comprehension over a for loop?在python3.6中引入了格式化字符串文本,并且很容易成为用插值元素组成字符串的最快方法(即使它们是didn't start out that way)。在
我也尝试了[
itertools.starmap()
]和[operator.add()
]和[str.join()
],但这似乎没有竞争力:它确实随着更多元素的增加而改进;增加了100万个元素,
map(starmap(add, largelist))
以很小的优势获胜(133ms比140ms的链表连接理解)。在相关问题 更多 >
编程相关推荐