【问题标题】:How do you reverse the words in a string using python (manually)? [duplicate]如何使用python(手动)反转字符串中的单词? [复制]
【发布时间】:2011-10-08 05:20:48
【问题描述】:

可能重复:
Reverse the ordering of words in a string

我知道 python 已经为此提供了一些方法,但我试图了解当您只有列表数据结构可以使用时这些方法如何工作的基础知识。如果我有一个字符串hello world,我想创建一个新字符串world hello,我会怎么想?

然后,如果我可以用一个新列表来做,我将如何避免制作一个新列表并在原地做呢?

【问题讨论】:

  • This SO question 有你的答案和一些 Python 代码
  • 因为字符串是不可变的,所以你永远无法做到这一点
  • @JBernardo:可能是他要求array 的原因。

标签: python


【解决方案1】:

Split the string,创建一个reverse iterator,然后返回join

' '.join(reversed(my_string.split()))

如果您担心多个空格,请将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

我认为现在有更多的 Pythonic 方法可以做到这一点(可能是 groupby)并且原始来源有一个错误(if i = n:,更正为==

【讨论】:

  • 如果我必须对它进行编程,它是如何工作的?
  • @cfarm reverse 返回一个迭代器。您必须将容器从它的大小循环到零,yielding 值
  • 拆分是如何工作的?你能写出拆分和反转的代码吗?
  • split 通过迭代字符串并找到分隔符来创建列表。您不想自己编写代码(尽管它会很简单),因为太慢并且需要重新发明轮子。
【解决方案2】:

原答案

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

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

除了重命名,唯一感兴趣的变化是最后一行。

【讨论】:

  • words = array('c', string) 是做什么的?
  • @cfarm54:它创建一个array 对象,其中包含string 中的任何内容,类型为字符。查看docs
  • 所以现在这对我来说不太适用。如果string = "hello world",那么len(words) 是11。
  • @cfarm54:你期待什么?如果string = "hello world" 你回来"world hello",这就是你要求的。
  • @cfarm54: len(words) 是 11 个,因为 words 是一个由 11 个字符组成的字符串——你确实说过你想要一个字符串。哦,更新了我的答案以使用列表而不是数组。
【解决方案3】:

你有一个字符串:

str = "A long string to test this algorithm"

拆分字符串(在单词边界——split 没有参数):

splitted = str.split()

反转获得的数组——使用范围或函数

reversed = splitted[::-1]

用空格连接所有单词——也称为连接。

result = " ".join(reversed)

现在,您不需要这么多临时变量,将它们组合成一行给出:

result = " ".join(str.split()[::-1])

【讨论】:

  • 我不明白为什么这被否决了。它遍历了 OP 想要澄清的现有答案的步骤,并得出了相同的正确结果。
  • @KarlKnechtel:除了没有按要求回答问题外,它们都是不错的答案——它们都不使用数组。
【解决方案4】:
str = "hello world"
" ".join(str.split()[::-1])

【讨论】:

  • 你能解释一下这里的逻辑吗?另外,如问题中所示,我试图了解仅使用数组执行此操作的基础知识。含义以str = 'hello world' 开头,然后创建一个数组并反转单词。
  • 使用内置函数将字符串拆分为单词。使用 [::-1] 切片反转拆分列表,方式与您提出的另一个问题和链接副本中解释的方式相同。然后将反向的单词列表与空格连接在一起。请注意“列表”一词。在 Python 中,数组是完全不同的东西。
猜你喜欢
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
相关资源
最近更新 更多