gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:24:52 26 4
gpt4 key购买 nike

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

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']

关于python - 使用 Python 在句子中反转单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58356702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com