指定されたブロックサイズに基づいて文字列を逆にしようとしています
例えば
"the price of food is 12 dollars"
そして、ブロックサイズ4が与えられます
最終結果を次のようにしたい:
food of price the dollars 12 is
これをPythonに入力する方法がわからないので、助けていただければ幸いです。任意のブロックサイズで機能するためにこれが必要です
指定されたブロックサイズに基づいて文字列を逆にしようとしています
例えば
"the price of food is 12 dollars"
そして、ブロックサイズ4が与えられます
最終結果を次のようにしたい:
food of price the dollars 12 is
これを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))
Related: How do you split a list into evenly sized chunks in Python?
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'
基本的に、リストを分割し、逆にしてから回転させます。
したがって、これは機能します:
>>> 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'