基于python中的块大小在python中反转字符串

use*_*942 5 python python-2.7

我试图根据给定的块大小来反转字符串

例如

"the price of food is 12 dollars" 并且我的块大小为4

我希望最终结果是:

food of price the dollars 12 is
Run Code Online (Sandbox Code Playgroud)

我不知道如何将此输入到python任何帮助将不胜感激我需要这个适用于任何块大小

wim*_*wim 6

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)

相关:如何在Python中将列表拆分为大小均匀的块?

  • 是的,你只是...呃......把它变成一个功能,祝你好运 (3认同)

jam*_*lak 5

使用itertools石斑鱼配方:

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