[英]Merging list items python 3.6
A python list consist of a number of items that is equally divided by 3. python列表由许多项组成,这些项平均除以3。
The list looks like this: 该列表如下所示:
the_list = ['ab','cd','e','fgh','i', 'jklm']
I want to merge 3 items at the time for the entire list. 我想在整个列表中同时合并3个项目。 How should I do that?
我应该怎么做? (the list could have any number of items as long as the number of items can be divided by 3)
(列表中可以包含任意数量的项目,只要可以将项目数除以3)
expected_output = ['abcde', 'fghijklm']
You can slice the list while iterating an index over the length of the list with a step of 3 in a list comprehension: 您可以在列表理解中以3的步长在列表长度上迭代索引时对列表进行切片:
[''.join(the_list[i:i + 3]) for i in range(0, len(the_list), 3)]
You can also create an iterator from the list and use zip
with itertools.repeat
to group 3 items at a time: 您还可以从列表中创建一个迭代器,并将
zip
与itertools.repeat
一起使用,以一次将3个项目分组:
from itertools import repeat
i = iter(the_list)
[''.join(t) for t in zip(*repeat(i, 3))]
Both of the above return: 以上两种返回:
['abcde', 'fghijklm']
这是使用列表理解和range
的一种方法:
output = [''.join(the_list[i:i+3]) for i in range(0, len(the_list), 3)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.