【问题标题】:Understanding list indexing errors了解列表索引错误
【发布时间】:2016-05-09 08:09:25
【问题描述】:

假设我有一个清单:

a = ['what','now','what','now','what','now']

现在如果我这样做:

for x in range(2, len(a)):
    if a[x:x+1] == a[x-2:x-1]:
        print True

我收到True, True, True, True

现在如果我这样做:

for x in range(2, len(a)):
    if a[x] == a[x-2] and a[x+1] == a[x-1]:
        print True

我收到True, True, True, Traceback (most recent call last):..IndexError: list index out of range

这两者不应该产生相同的结果吗?这里发生了什么?

【问题讨论】:

  • 允许切片超出列表的末尾,但不允许直接索引。

标签: python list indexing


【解决方案1】:

问题在于,在第二个中,您正在执行x+1,恰好是 6。

以下是您将来如何看待它:

for x in range(2, len(a)):
    try:
        if a[x] == a[x-2] and a[x+1] == a[x-1]:
            print True
    except Exception, e:
        print x

要解决问题,你可以这样做

for x in range(2, len(a)-1):
    try:
        if a[x] == a[x-2] and a[x+1] == a[x-1]:
            print True
    except Exception, e:
        print x

【讨论】:

    【解决方案2】:

    在第一个示例中,a[x:x+1] 不包括 len(a) + 1。 在第二个示例中,a[x+1] 超出范围。

    【讨论】:

      【解决方案3】:

      您始终可以使用列表之外的索引进行切片:

      >>> a = ['what','now','what','now','what','now']
      >>> a[3:100]
      ['now', 'what', 'now']
      

      这里和a[3:]的效果一样。

      但是当你访问一个列表范围之外的索引时,你会得到一个索引错误:

      >>> a[100]
      IndexError: list index out of range
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-26
        • 2017-08-30
        • 1970-01-01
        • 2018-08-29
        • 2014-08-11
        • 2023-04-05
        • 2015-04-27
        • 2022-01-20
        相关资源
        最近更新 更多