python - 在python中反转句子

标签 python loops indexing

<分区>

谢谢大家的回答。我知道为什么我的代码是错误的。

请不要向我提供解决方案,因为我确实有一些解决方案,但我想了解我的代码无法正常工作。

我认为这是由于 while x <= -len(split_result):"但后来我认为逻辑是正确的。我的代码有什么问题?

O_string = ("Me name is Mr_T")
split_result = O_string.split()
print(split_result)

x=0
list=[]

while x <= -len(split_result):
    list.append(split_result[x-1])
    x = x-1

result=" ".join(list)
print (result)

最佳答案

您可以使用 [::-1] 反转列表:

print(' '.join(O_string.split()[::-1]))

输出:

'Mr_T is name Me'

这里的[::-1]表示从头到尾以负一的步长获取所有内容。

或者,您可以使用内置函数reversed:

>>> ' '.join(reversed(O_string.split()))
'Mr_T is name Me'

关于你的算法。在我看来,以负指数思考总是更困难。我会建议去积极的:

O_string = ("Me name is Mr_T")
split_result = O_string.split()

res = []
x = len(split_result) - 1
while x >= 0:
    res.append(split_result[x])
    x = x-1

result=" ".join(res)
print (result) 

输出:

'Mr_T is name Me'

这里:

x = len(split_result) - 1

为您提供列表的最后一个索引。我们从 0 开始索引。因此,您需要从列表的长度中减去 1

你倒数:

x = x-1

一旦得到负指数就停止:

while x >= 0:

提示:不要使用list 作为变量名。它是内置的,最好不要用于命名自己的对象。如果这样做,您将无法再轻松地使用 list()(在相同的命名空间中)。

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

相关文章:

python - Xpath 用于使用类查找 anchor 标记内的文本(Scrapy)

python:根据原始索引添加列表元素(同时更新列表)

python - python 中的 IRC 客户端

Python - 心理数学测试(这可以更有效吗?)

python - raspberrypi 电子邮件通知程序 - 找不到 py 命令

r - 如何合并数据集而不在一个有多个值的地方循环?

javascript - javascript 中的 foreach 循环语法

ios - IPA安装循环

indexing - 是否可以在 RavenDb 5+ 中计算时间序列的移动平均线/EMA/窗口聚合?

postgresql - Postgres hstore : GIN vs GiST index performance