Skip to main content
 首页 » 编程设计

python之使用 Python 在句子中反转单词

2025年05月04日18bjzhanghao

我正在尝试反转句子中的单词。

for example:

arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', '  ', 
        'm', 'a', 'k', 'e', 's', '  ', 
        'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ] 

should be

[ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', '  ', 
  'm', 'a', 'k', 'e', 's', '  ', 
  'p', 'e', 'r', 'f', 'e', 'c', 't' ] 

我写了下面的代码,先反转整个数组然后反转每个单词

def reverse_words(arr): 
 
  def mirrorReverse(arr,start,end): 
    while(start<end): 
      tmp=arr[start] 
      arr[start]=arr[end] 
      arr[end]=tmp 
      start+=1 
      end-=1 
 
  n=len(arr) 
  mirrorReverse(arr,0,n-1) 
 
  for i in range(len(arr)): 
    if arr[i]=='  ' and start==0: #first word 
      mirrorReverse(arr,start,i-1) 
      start=i+1 
    elif i==len(arr)-1: #last word   
      mirrorReverse(arr,start,i) 
 
    elif arr[i]=='  ' and start!=None: #middle 
        mirrorReverse(arr,start,i-1) 
        start=i+1 
 
  return arr   

这工作正常并输出所需的答案但是当我使用不同的示例时它不起作用:

test 1: ["a"," "," ","b"]

Expected: ["b"," "," ","a"]

Actual: ['a', ' ', ' ', 'b']

test2: ["y","o","u"," ","w","i","t","h"," ","b","e"," ","f","o","r","c","e"," ","t","h","e"," ","m","a","y"]

output: ['y', 'o', 'u', ' ', 'w', 'i', 't', 'h', ' ', 'b', 'e', ' ', 'f', 'o', 'r', 'c', 'e', ' ', 't', 'h', 'e', ' ', 'm', 'a', 'y']

尽管 test2 与上面的主要示例相似,但效果非常好。任何帮助

请您参考如下方法:

首先,在 Python 提示符下:

>>> def revwords(str): 
...    list = str.split() 
...    list.reverse() 
...    return ' '.join(list) 
...  
>>> revwords('The quick brown fox jumped over the lazy dogs.') 
'dogs. lazy the over jumped fox brown quick The' 

通过进行一些重组和拆分,我们可以将上述内容与所需的字符数组表示形式一起使用。在 Python 提示符处继续:

>>> list(revwords(''.join(['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']))) 
['w', 'o', 'r', 'l', 'd', ' ', 'H', 'e', 'l', 'l', 'o']