我试图根据给定的块大小来反转字符串
例如
"the price of food is 12 dollars" 并且我的块大小为4
我希望最终结果是:
food of price the dollars 12 is
Run Code Online (Sandbox Code Playgroud)
我不知道如何将此输入到python任何帮助将不胜感激我需要这个适用于任何块大小
def chunks(seq, n):
return [seq[i:i+n] for i in range(0, len(seq), n)]
s = "the price of food is 12 dollars"
' '.join(' '.join(reversed(chunk)) for chunk in chunks(s.split(), 4))
Run Code Online (Sandbox Code Playgroud)
>>> from itertools import izip_longest
>>> def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
>>> text = "the price of food is 12 dollars"
>>> ' '.join(word for g in grouper(4, text.split())
for word in reversed(g) if word)
'food of price the dollars 12 is'
Run Code Online (Sandbox Code Playgroud)