我想在元组列表中连接两个字符串元素
我有这个:
mylist = [(‘a’,‘b’),(‘c’,‘d’),(‘e’,‘f’),(‘g’,‘h’)]myanswer = []
对于mylist中的tup1: myanswer.append(tup1 [0] …
使用列表推导,对于两个元素,我将使用元组解包和连接:
myanswer = [s1 + s2 for s1, s2 in mylist]
另一个选择是使用a 格式化字符串文字 :
myanswer = [f"{s1}{s2}" for s1, s2 in mylist]
两者都相当快:
>>> 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
连接在这里胜出。
列表理解消除了查找列表对象及其的需要 .append() 每次在循环中的方法,请参阅 列表理解优于for循环的优势是什么?
.append()
Python 3.6中引入的格式化字符串文字,很容易用插值元素组成字符串的最快方法(即使它们 并没有这样开始 )。
我也尝试过[ itertools.starmap() ] [带] operator.add() ]和[ str.join() ],但这似乎没有竞争力:
itertools.starmap()
operator.add()
str.join()
>>> count, total = Timer('list(starmap(add, mylist))', 'from __main__ import testdata as mylist; from itertools import starmap; from operator import add').autorange() >>> print(f"itertools.starmap and operator.add, 10k elements: {total / count * 1000000:6.2f} microseconds") itertools.starmap and operator.add, 10k elements: 1275.02 microseconds >>> count, total = Timer('list(starmap(str.join, mylist))', 'from __main__ import testdata as mylist; from itertools import starmap').autorange() >>> print(f"itertools.starmap and str.join, 10k elements: {total / count * 1000000:6.2f} microseconds") itertools.starmap and str.join, 10k elements: 1564.79 microseconds
它确实随着更多元素而改进;百万元素, map(starmap(add, largelist)) 以小幅度获胜(133ms与140ms相比,列表理解与连接)。
map(starmap(add, largelist))