1

我有一个这样的列表:

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

并继续以这种模式,使用不同的大写和小写。我想要做的是将这个列表中的每四个项目连接在一起。因此,生成的新列表(给定上面的列表)如下所示:

['WwAaBbCc', "wwAABBCC']

我该怎么办?

4

3 回答 3

4
>>> L = ['Ww','Aa','Bb','Cc','ww','AA','BB','CC']
>>> [''.join(x) for x in zip(*[iter(L)] * 4)]
['WwAaBbCc', 'wwAABBCC']
于 2012-04-10T04:01:28.017 回答
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)]
于 2012-04-10T04:00:49.190 回答
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']
于 2012-04-10T04:10:06.100 回答