可能重复:
反转字符串中单词的顺序
我知道python已经为此提供了一些方法,但我正在尝试理解当你只使用列表数据结构时这些方法如何工作的基础知识.如果我有一个字符串hello world并且我想创建一个新字符串world hello,我该怎么想?
然后,如果我可以使用新列表,我将如何避免制作新列表并在适当的位置执行此操作?
JBe*_*rdo 14
' '.join(reversed(my_string.split()))
Run Code Online (Sandbox Code Playgroud)
如果您担心多个空格,请更改split()为split(' ')
根据要求,我发布了一个split的实现(由GvR自己从最古老的CPython可下载版本的源代码:Link)
def split(s,whitespace=' \n\t'):
res = []
i, n = 0, len(s)
while i < n:
while i < n and s[i] in whitespace:
i = i+1
if i == n:
break
j = i
while j < n and s[j] not in whitespace:
j = j+1
res.append(s[i:j])
i = j
return res
Run Code Online (Sandbox Code Playgroud)
我想现在有更多的pythonic方法(也许是groupby)和原始来源有一个bug(if i = n:,更改==)
原始答案
from array import array
def reverse_array(letters, first=0, last=None):
"reverses the letters in an array in-place"
if last is None:
last = len(letters)
last -= 1
while first < last:
letters[first], letters[last] = letters[last], letters[first]
first += 1
last -= 1
def reverse_words(string):
"reverses the words in a string using an array"
words = array('c', string)
reverse_array(words, first=0, last=len(words))
first = last = 0
while first < len(words) and last < len(words):
if words[last] != ' ':
last += 1
continue
reverse_array(words, first, last)
last += 1
first = last
if first < last:
reverse_array(words, first, last=len(words))
return words.tostring()
Run Code Online (Sandbox Code Playgroud)
使用答案list来匹配更新的问题
def reverse_list(letters, first=0, last=None):
"reverses the elements of a list in-place"
if last is None:
last = len(letters)
last -= 1
while first < last:
letters[first], letters[last] = letters[last], letters[first]
first += 1
last -= 1
def reverse_words(string):
"""reverses the words in a string using a list, with each character
as a list element"""
characters = list(string)
reverse_list(characters)
first = last = 0
while first < len(characters) and last < len(characters):
if characters[last] != ' ':
last += 1
continue
reverse_list(characters, first, last)
last += 1
first = last
if first < last:
reverse_list(characters, first, last=len(characters))
return ''.join(characters)
Run Code Online (Sandbox Code Playgroud)
除了重命名之外,唯一感兴趣的变化是最后一行.
您有一个字符串:
str = "A long string to test this algorithm"
Run Code Online (Sandbox Code Playgroud)
分割字符串(在字边界处-不含参数split):
splitted = str.split()
Run Code Online (Sandbox Code Playgroud)
反转获得的数组-使用范围或函数
reversed = splitted[::-1]
Run Code Online (Sandbox Code Playgroud)
将所有单词之间用空格连接-也称为连接。
result = " ".join(reversed)
Run Code Online (Sandbox Code Playgroud)
现在,您不需要那么多的温度,将它们组合成一行即可得到:
result = " ".join(str.split()[::-1])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19256 次 |
| 最近记录: |