有效地连接列表中元组中的两个字符串?

2024-09-28 21:56:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想连接元组列表中的两个字符串元素

我有这个:

mylist = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
myanswer = []

for tup1 in mylist:
   myanswer.append(tup1[0] + tup[1])

它是有效的,但有什么简单的方法来做到这一点?我真正的列表有大约1000个条目,我不认为for循环是最有效的方法。在

预期产量:

^{pr2}$

Tags: 方法字符串in元素列表for条目元组
1条回答
网友
1楼 · 发布于 2024-09-28 21:56:33

使用列表理解,对于两个元素,我将使用元组解压和连接:

myanswer = [s1 + s2 for s1, s2 in mylist]

另一个选择是使用formatted string literal

^{pr2}$

两者都相当快:

>>> 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()方法的需要,请参见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()],但这似乎没有竞争力:

>>> 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

它确实随着更多元素的增加而改进;增加了100万个元素,map(starmap(add, largelist))以很小的优势获胜(133ms比140ms的链表连接理解)。在

相关问题 更多 >