5

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

例如

"the price of food is 12 dollars"我给定一个块大小为 4

我希望最终结果是:

food of price the dollars 12 is

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

4

3 回答 3

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

Related: How do you split a list into evenly sized chunks in Python?

于 2013-04-12T05:31:04.967 回答
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'
于 2013-04-12T05:27:44.030 回答
1

您实际上是在拆分列表,反转它,然后旋转它。

所以这有效:

>>> st='the price of food is 12 dollars'
>>> li=st.split()[::-1]
>>> n=3
>>> print ' '.join(l[n:]+l[:n])
food of price the dollars 12 is

或者,更直接地:

>>> li='the price of food is 12 dollars'.split()[::-1]
>>> print ' '.join(li[3:]+li[:3])
food of price the dollars 12 is

或者,如果你想在一个函数中使用它:

def chunk(st,n):
    li=st.split()[::-1]  # split and reverse st
    return ' '.join(li[n:]+li[:n])

print chunk('the price of food is 12 dollars',3)    

关键是:

st='the price of food is 12 dollars'  # the string
li=st.split()                         # split that
li=li[::-1]                           # reverse it
li=li[3:]+li[:3]                      # rotate it
' '.join(li)                          # produce the string from 'li'
于 2013-04-12T06:07:41.473 回答