我发现了一个很棒的回文代码,我可以抽象地理解,但我不确定它是如何工作的。
def palindrome(word):
return word == word[::-1]
我认为单词的数据类型是“字符串”而不是“列表”。但在该代码中,它将单词视为列表类型。它会自动将 word
更改为 list(word)
吗?
最佳答案
Python 切片表示法非常简单。取自另一个answer :
a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array
a[start:stop:step] # start through not past stop, by step
举个例子:
word = 'abcd'
assert word[0] == 'a'
assert word[0:3] == 'abc'
assert word[0:4] == 'abcd'
assert word[0:4:2] == 'ac'
在您的情况下,如果步骤是-1
,那么它会向后退:
assert word[::-1] = 'dcba'
因此,如果一个单词向后等于单词本身,那么它就是回文:
if word == word[::-1]:
return True
关于python - 这个将 'string' 视为 'list' 的回文代码如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944912/