加入列表中的每四个字符串

时间:2012-04-10 03:56:11

标签: python list join

我有一个这样的清单:

['Ww','Aa','Bb','Cc','ww','AA','BB','CC']

继续这种模式,不同的资本和低层。 我想要做的是将这个列表中的每四个项目加在一起。因此,生成的新列表(如上所示)将如下所示:

['WwAaBbCc', "wwAABBCC']

我该怎么做?

3 个答案:

答案 0 :(得分:4)

>>> L = ['Ww','Aa','Bb','Cc','ww','AA','BB','CC']
>>> [''.join(x) for x in zip(*[iter(L)] * 4)]
['WwAaBbCc', 'wwAABBCC']

答案 1 :(得分:3)

my_list = ['Ww','Aa','Bb','Cc','ww','AA','BB','CC']
[''.join(my_list[i:i + 4]) for i in range(0, len(my_list), 4)]

答案 2 :(得分:1)

您可以使用以下内容:

def _get_chunks(lVals, size):
    for i in range(0, len(lVals), size):
        yield lVals[i: i + size]

data = ['Ww','Aa','Bb','Cc','ww','AA','BB','CC']


output = [''.join(chunk) for chunk in _get_chunks(data, 4)]
>>> ['WwAaBbCc', 'wwAABBCC']