Most pythonic way to interleave two strings(交错两个字符串的最pythonic方法)
问题描述
将两个字符串连接在一起的最 Pythonic 方式是什么?
What's the most pythonic way to mesh two strings together?
例如:
输入:
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'
输出:
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
推荐答案
对我来说,最 Pythonic* 的方法是以下 几乎做同样的事情,但使用 + 用于连接每个字符串中的单个字符的运算符:
For me, the most pythonic* way is the following which pretty much does the same thing but uses the + operator for concatenating the individual characters in each string:
res = "".join(i + j for i, j in zip(u, l))
print(res)
# 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
它也比使用两个 join() 调用更快:
It is also faster than using two join() calls:
In [5]: l1 = 'A' * 1000000; l2 = 'a' * 1000000
In [6]: %timeit "".join("".join(item) for item in zip(l1, l2))
1 loops, best of 3: 442 ms per loop
In [7]: %timeit "".join(i + j for i, j in zip(l1, l2))
1 loops, best of 3: 360 ms per loop
存在更快的方法,但它们经常混淆代码.
Faster approaches exist, but they often obfuscate the code.
注意:如果两个输入字符串不同长度相同,那么较长的字符串将被截断为zip 在较短字符串的末尾停止迭代.在这种情况下,应该使用 而不是 (zipzip_longestizip_longest 在 Python 2) 中来自 itertools 模块以确保两个字符串都完全耗尽.
Note: If the two input strings are not the same length then the longer one will be truncated as zip stops iterating at the end of the shorter string. In this case instead of zip one should use zip_longest (izip_longest in Python 2) from the itertools module to ensure that both strings are fully exhausted.
*引用 Python 之禅:可读性很重要.
Pythonic = 可读性 对我来说;i + j 只是在视觉上更容易解析,至少对我来说是这样.
*To take a quote from the Zen of Python: Readability counts.
Pythonic = readability for me; i + j is just visually parsed more easily, at least for my eyes.
这篇关于交错两个字符串的最pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:交错两个字符串的最pythonic方法
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
