gpt4 book ai didi

Python 列表及其拆分

转载 作者:太空狗 更新时间:2023-10-30 01:41:45 24 4
gpt4 key购买 nike

比如我有这样的代码

a = ["a;b", "c;d",...,"y;z"]

我想将每个列表元素拆分成同一个列表的项目。所以我想得到这样的东西:

["a", "b", "c", "d", ...., "y", "z"]

我该怎么做?感谢您的回答。

最佳答案

仅使用字符串操作似乎是最简单(当然,这是主观的)和最快(与目前发布的其他解决方案相比,差距很大)。

>>> a = ["a;b", "c;d", "y;z"]
>>> ";".join(a).split(";")
['a', 'b', 'c', 'd', 'y', 'z']

证明/基准

按运行时间升序排列:

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' '";".join(a).split(";")'
10000 loops, best of 3: 48.2 usec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' '[single for pair in a for single in pair.split(";")]'
1000 loops, best of 3: 347 usec per loop

python -mtimeit -s'from itertools import chain; a=["a;b","x;y","p;q"]*99' 'list(chain(*(s.split(";") for s in a)))'
1000 loops, best of 3: 350 usec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'sum([x.split(";") for x in a],[])'
1000 loops, best of 3: 1.13 msec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'sum(map(lambda x: x.split(";"), a), [])'
1000 loops, best of 3: 1.22 msec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'reduce(lambda x,y:x+y, [pair.split(";") for pair in a])'
1000 loops, best of 3: 1.24 msec per loop

关于Python 列表及其拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com