I have a sample list of strings:
my_list = ['hello','this','is','a','sample','list', 'thanks', 'for', 'help']
And I want to club every three elements together, like:
new_list = ['hello this is', 'a sample list', 'thanks for help']
I have a sample list of strings:
my_list = ['hello','this','is','a','sample','list', 'thanks', 'for', 'help']
And I want to club every three elements together, like:
new_list = ['hello this is', 'a sample list', 'thanks for help']
Just split into chunks and join:
[' '.join(my_list[i:i+3]) for i in range(0, len(my_list), 3)]
my_list
length is not divisible by 3input string: ['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']
[" ".join(i) for i in zip(*[iter(my_list)]*3)]
result: ['hello this is', 'a sample list', 'thanks for help']
how python iter trick works: How does zip(*[iter(s)]*n) work in Python?
zip_longest
input string: ['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']
[" ".join(i) for i in zip_longest(*[iter(my_list)]*3, fillvalue='')]
result: ['hello this is', 'a sample list', 'thanks for help', 'foo ']
You can solve this by iterating using a step, in this case 3 steps, and adding the individual strings under each step, i.e., my_list[i]
, my_list[i+1]
. my_list[i+2 ]
. Note that you need to add a space after each first and second string. This piece of code does that:
new_list = []
for i in range(0, len(my_list), 3):
if i + 2 < len(my_list):
new_list.append(my_list[i] + ' ' + my_list[i+1] + ' ' + my_list[i+2])
print(new_list)
The output is as expected:
['hello this is', 'a sample list', 'thanks for help']
A couple of solutions using itertools
are possible.
Using groupby
:
[' '.join(x[1] for x in g) for _, g in groupby(enumerate(my_list), lambda x: x[0] // 3)]
Using tee
and zip_longest:
a, b = tee(my_list)
next(b)
b, c = tee(b)
next(c)
[' '.join(items) for items in zip_longest(a, b, c, fillvalue='')]
Using just zip_longest
:
[' '.join(g) for g in zip_longest(*[iter(my_list)] * 3, fillvalue='')]
The last two are adapted from the pairwise
and grouper
recipes in the documentation. Only the first option won't add extra spaces at the end of your last group if the aren't a multiple of 3 words.