python单词反转_如何使用python(手动)反转字符串中的单词?

原始答案

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

使用列表回答更新的问题

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)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值