简体   繁体   English

为什么我的reverse()方法在python 3中不起作用?

[英]Why my reverse() method doesn't work in python 3?

I was trying to do this exercise where you have to take a word and check if it's a palindrome. 我正在尝试进行此练习,您必须说一句话并检查是否是回文。 I tried to do it with making a string in to a list then reversing it and turning it back to a string, but the reverse method doesn't work for me for some reason, I checked and the usage is correct. 我尝试通过将字符串放入列表中然后将其反转然后将其返回为字符串来完成此操作,但是由于某种原因,反向方法对我不起作用,我检查了一下用法是否正确。

word = input('Give me a word:\n')
b = []
wordLetters = word.split()
b = wordLetters.reverse()
word2 = ''.join(b)

if word == word2:
    print('Yay')
else:
    print('heck')

it just shows 它只是显示

TypeError: can only join an iterable TypeError:只能加入可迭代

list()的reverse()方法不返回任何内容,但会在Python 3中本身反转列表。因此,请加入wordLetters而不是b。希望这可以解决问题。

In Python reverse method of list does the operation in-place eg it modifies the list you apply this operation to. 在Python的list reverse方法中,该操作是就地进行的,例如,它修改了对此操作应用的列表。 This method has no return value. 此方法没有返回值。

l = [1, 2, 3, 4]
l.reverse()
print(l)

Output: 输出:

[4, 3, 2, 1]

If you try to get value returned by reverse you will get None : 如果您尝试获取reverse返回的值,则会得到None

print([1, 2, 3, 4].reverse())

Output: 输出:

None

If you need a reversed copy of your list you should use reversed function: 如果需要列表的反向副本,则应使用reversed函数:

l = [1, 2, 3, 4]
r = reversed(l)
print(r)
print(list(r))

Output: 输出:

<list_reverseiterator object at 0x7ff37e288ef0>
[4, 3, 2, 1]

Notice that it returns iterator, not the list itself. 请注意,它返回迭代器,而不是列表本身。 You can pass that iterator to join function or you can build a list from it using list constructor. 您可以传递该迭代器以join函数,也可以使用list构造函数从中构建一个列表。

The same is true for method sort and function sorted . 方法sort和函数sorted也是如此。

As the documentation states: 文档所述:

list.reverse() list.reverse()

Reverse the elements of the list in place. 反转列表中的元素。

That means this method won't return anything (otherwise it would state what it returns) and that it reverses the list in-place. 这意味着此方法将不会返回任何内容(否则它将声明其返回的内容),并且会就地反转列表。

Also str.split will (by default) split at whitespaces which is probably not intended from the problem description. 同样, str.split (默认情况下)也会在空格处分割,这可能不是问题描述所希望的。

My suggestion would be to simply use slice notation for reversing the string: 我的建议是简单地使用切片符号来反转字符串:

word = input('Enter your word')
if word == word[::-1]:
    print('Yay')
else:
    print('heck')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM