我有一个字符串列表,我想按以下方式连接列表的元素:
之前 = ['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/