连接列表中的成对元素-Python [英] Joining pairs of elements of a list - Python

查看:90
本文介绍了连接列表中的成对元素-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以将一个列表连接成一个长字符串,如下所示:

I know that a list can be joined to make one long string as in:

x = ['a', 'b', 'c', 'd']
print ''.join(x)

显然,这将输出:

'abcd'

但是,我想做的只是将列表中的第一个和第二个字符串连接在一起,然后连接第三个和第四个字符串,依此类推.简而言之,从上面的示例中取而代之的是:

However, what I am trying to do is simply join the first and second strings in the list, then join the third and fourth and so on. In short, from the above example instead achieve an output of:

['ab', 'cd']

有没有简单的方法可以做到这一点?我可能还应该提到,列表中字符串的长度以及列表中字符串的数量都是不可预测的,尽管字符串的数量始终是偶数.因此原始列表也可能是:

Is there any simple way to do this? I should probably also mention that the lengths of the strings in the list will be unpredictable, as will the number of strings within the list, though the number of strings will always be even. So the original list could just as well be:

['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'] 

推荐答案

您可以在步骤中使用切片符号:

You can use slice notation with steps:

>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
'acegikm'
>>> x[1::2] #1. 3. 5 ..
'bdfhjl'
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

相同的逻辑也适用于列表.字符串长度无关紧要,因为您只是将两个字符串加在一起.

Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.

这篇关于连接列表中的成对元素-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆