简体   繁体   中英

Merging list items python 3.6

A python list consist of a number of items that is equally divided by 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. 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)

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:

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

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM