我的问题有什么不同的方法?

Ali*_*far 6 python python-3.x

我是 python 新手,遇到了一个问题:我的任务是 "Given a sentence, return a sentence with the words reversed"

例如 Tea is hot --------> hot is Tea

我的代码是:

def funct1 (x):
    a,b,c = x.split()
    return c + " "+  b + " "+ a

funct1 ("I am home")
Run Code Online (Sandbox Code Playgroud)

它确实解决了答案,但我有两个问题:

  1. 如何在不添加空格连接的情况下提供空间
  2. 除了拆分还有其他方法可以逆转吗?

谢谢你。

Dee*_*ace 5

您的代码在很大程度上依赖于假设字符串将始终包含正好2个空格。您提供的任务描述并没有说情况总是如此。

这个假设可以通过使用str.join[::-1]反转列表来消除:

def funct1(x):
    return ' '.join(x.split()[::-1])

print(funct1('short example'))
print(funct1('example with more than 2 spaces'))
Run Code Online (Sandbox Code Playgroud)

输出

example short
spaces 2 than more with example
Run Code Online (Sandbox Code Playgroud)

可以使用 进行微优化reversed,因此不需要创建额外的列表:

return ' '.join(reversed(x.split()))
Run Code Online (Sandbox Code Playgroud)

2)除了拆分还有其他方法可以逆转吗?

由于要求是颠倒单词的顺序,同时保持每个单词内部的字母顺序,所以这个问题的答案是“不是真的”。可以使用正则表达式,但这与在空格上拆分会有很大不同吗?可能不是。split无论如何,使用可能会更快。

import re

def funct1(x):
    return ' '.join(reversed(re.findall(r'\b(\w+)\b', x)))
Run Code Online (Sandbox Code Playgroud)