Python反转列表

50
我想要将一个字符串反转,使用以下代码,但最终反转后的列表值为None。
代码如下:
str_a = 'This is stirng'
rev_word = str_a.split()
rev_word = rev_word.reverse()
rev_word = ''.join(rev_word)

它返回了TypeError。为什么?


6
这里已经有答案了吗?(个人喜欢那里的 ''.join(reversed(s)) 解决方案。) - ron rothman
1
我希望#reverse返回一个对self的引用。 我猜Guido van Rossum不像Yukihiro Matsumoto那样喜欢方法链接。 - Eric Walker
8个回答

123

这是我个人最喜欢的反转字符串的方法:

stra="This is a string"
revword = stra[::-1]

print(revword) #"gnirts a si sihT

或者,如果你想要颠倒单词顺序:

revword = " ".join(stra.split()[::-1])

print(revword) #"string a is This"

:)


我知道它能工作。但是我期望得到“T”,因为我们没有指定起始和结束,我期望Python从0开始向后移动。请告诉我它是如何工作的。 - thefourtheye
@thefourtheye 请查看这个stackoverflow链接:https://dev59.com/D3RB5IYBdhLWcg3wyqOo - Sean Johnson
@SeanJohnson 那么,如果我们将步长值设为-1,默认情况下它会向后遍历。这样对吗? - thefourtheye

53

.reverse() 方法返回的是None,因此你不应该将其赋值给变量。

应该使用以下代码:

stra = 'This is a string'
revword = stra.split()
revword.reverse()
revword=''.join(revword)

我已经在IDEOne上为你运行了代码,以便你可以查看输出。(还请注意输出为stringaisThis;你可能需要使用' '.join(revword)来代替,加上一个空格。)

另外,请注意你提供的方法只是翻转单词,而不是整个文本。@ron.rothman提供了一个链接,详细介绍了如何完全翻转字符串。


7

字符串的各种翻转:

instring = 'This is a string'
reversedstring = instring[::-1]
print reversedstring        # gnirts a si sihT
wordsreversed = ' '.join(word[::-1] for word in instring.split())
print wordsreversed         # sihT si a gnirts
revwordorder = ' '.join(word for word in instring.split()[::-1])
print revwordorder          # string a is This
revwordandorder = ' '.join(word[::-1] for word in instring.split()[::-1])
print revwordandorder       # gnirts a si sihT

6

以后当一个对象有像[].reverse()这样的方法时,通常它会在该对象上执行该操作(例如,列表被排序并返回无值,None),与内置函数如sorted相反,它对一个对象执行操作并返回一个值(即排序后的列表)。


4
>>> s = 'this is a string'
>>> s[::-1]
'gnirts a si siht'
>>> ''.join(reversed(s))
'gnirts a si siht'

0
列表反转可以使用多种方法进行。如前面的答案中提到的,有两种非常突出的方法,一种是使用reverse()函数,另一种是使用切片功能。我将提供一些见解,说明我们应该选择哪种方法。
我们应该始终使用reverse()函数来反转Python列表。原因有两个:一是原地反转,二是比其他方法更快。
我有一些数据支持我的答案。
In [15]: len(l)
Out[15]: 1000

In [16]: %timeit -n1 l.reverse()
1 loops, best of 3: 7.87 µs per loop

In [17]: %timeit -n1 l[::-1]
1 loops, best of 3: 10 µs per loop

对于1000个整数列表,reverse()函数比切片表现更好。


0

基于评论和其他答案:

str_a = 'this is a string'
rev_word = ' '.join(reversed(str_a.split()))

方法链接在Python中确实可行...


0

for循环从字符串的末尾(最后一个字母)到开头(第一个字母)进行迭代

>>> s = 'You can try this too :]'
>>> rev = ''
>>> for i in range(len(s) - 1, -1, -1):
...     rev += s[i]
>>> rev
']: oot siht yrt nac uoY'

2
请考虑提供一些解释! - Konsole
rev是一个空字符串变量。 for循环将原始字符串向后迭代(从最后一个字母到第一个字母)。在每次迭代中,相应的字母被附加到rev。如果有帮助,请告诉我 :] - Aziz Alto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接