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

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

问题描述

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

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

显然这会输出:

'abcd'

但是,我想要做的只是连接列表中的第一个和第二个字符串,然后连接第三个和第四个字符串,依此类推.简而言之,从上面的例子改为实现输出:

['ab', 'cd']

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

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

解决方案

您可以使用带步骤的切片表示法:

<预><代码>>>>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 使 (0,1),(2,3) ...['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

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

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

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

Obviously this would output:

'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.

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

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