【问题标题】:how this palindrome code which treats 'string' as 'list' works?这个将“字符串”视为“列表”的回文代码如何工作?
【发布时间】:2020-01-16 14:04:19
【问题描述】:

我发现了一个很棒的回文代码,我可以抽象地理解,但我不确定它是如何工作的。

def palindrome(word):
    return word == word[::-1]

我认为 word 的数据类型是“字符串”而不是“列表”。但在该代码中,它将 word 视为列表类型。是否会自动将word 更改为list(word)

【问题讨论】:

  • 看到这个answer
  • @Jaehyun Kim,python 可以将字符串视为数组。

标签: python python-3.x string


【解决方案1】:

序列的子序列称为切片,提取子序列的操作称为切片。与索引一样,我们使用方括号 ([ ]) 作为切片运算符,但内部不是一个整数值,而是两个整数值,由冒号 (:) 分隔:

>>> singers = "Peter, Paul, and Mary"
>>> singers[0:5]
'Peter'
>>> singers[7:11]
'Paul'
>>> singers[17:21]
'Mary'
>>> classmates = ("Alejandro", "Ed", "Kathryn", "Presila", "Sean", "Peter")
>>> classmates[2:4]
('Kathryn', 'Presila')

运算符 [n:m] 返回序列中从第 n 个元素到第 m 个元素的部分,包括第一个但不包括最后一个。这种行为是违反直觉的;如果您想象索引指向字符之间,则更有意义,如下图所示:

'香蕉'字符串

如果省略第一个索引(在冒号之前),则切片从字符串的开头开始。如果省略第二个索引,则切片将转到字符串的末尾。因此:

>>> fruit = "banana"
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

你认为 s[:] 是什么意思?同学们[4:]呢?

负索引也是允许的,所以

>>> fruit[-2:]
'na'
>>> classmates[:-2]
('Alejandro', 'Ed', 'Kathryn', 'Presila')

source

【讨论】:

    【解决方案2】:

    字符串的行为类似于可切片的 sequences

    【讨论】:

    • 这是否意味着您可以在任何可迭代对象上使用切片?我认为情况并非如此。
    • 你是对的(见question),它看起来像是对序列进行切片(我编辑了我的答案)。
    【解决方案3】:

    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'
    

    在你的情况下,如果 step 是 -1 那么它会倒退:

    assert word[::-1] = 'dcba'
    

    所以如果一个单词backward等于单词本身那么它就是回文:

    if word == word[::-1]:
        return True
    

    【讨论】:

      【解决方案4】:

      查看 Python 字符串的一种方法是有序的字符序列。它们支持使用方括号表示法进行索引和切片,例如s[...]。这也意味着您可以遍历它们,并使用in 测试成员资格。

      看看这个问题:What exactly are iterator, iterable, and iteration?

      【讨论】:

      • 感谢您的回答。实际上,我对在字符串上使用 [] 感到困惑。 'ape' 是否与括号符号中的 ['a','p','e'] 同等对待?
      • 或多或少,就索引和切片而言。但是字符串有不同的方法(附加到它们的函数)。例如,您有s.upper()。但是没有append 方法(除其他外),因为您不能就地更改字符串。尝试做s = 'hello'; s[1] = 'a',你会发现你不能改变这样的字符串。 (但您可以更改列表。)
      猜你喜欢
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多