python - 如何在 Python 中按元素连接列表?

标签 python list

我有一个字符串列表,我想按以下方式连接列表的元素:

之前 = ['a', 'b', 'c', 'd']

之后 = ['ab', 'bc', 'cd']

我不确定上面的操作是如何调用的。

但是,我尝试使用范围方法:

after = [before[i]+before[i+1] for i in range(0,len(before),2)]

但结果是:after = ['ab', 'cd']

最佳答案

您的方法不允许重叠,因为您的索引增加了 2。

快速修复是

after = [before[i]+before[i+1] for i in range(len(before)-1)]

但我宁愿zip列表本身的切片版本:

before = ['a', 'b', 'c', 'd']

after = [a+b for a,b in zip(before,before[1:])]

>>> after
['ab', 'bc', 'cd']

关于python - 如何在 Python 中按元素连接列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53546120/

相关文章:

java - 从 Java 字符串列表中跟踪回文

c# - 如何检查字符串是否包含 List<string> 的任何元素?

python - 从列表中删除元素后释放内存

python - 如何创建 TensorFlow 变量的 Python 列表

python 3 : get 2nd to last index of occurrence in string

python - Sympy:求解微分方程

python - 添加矩阵python

python - 仅检测人类

python - 有没有一种简单的方法可以从 Python CGI 脚本启动后台任务而无需等待它终止?

string - 在 Fortran 中获取可变长度字符串列表的更好方法