简体   繁体   English

如何迭代python列表?

[英]How to iterate over a python list?

If I execute this code, the following error message occurs:如果我执行此代码,则会出现以下错误消息:

IndexError: list index out of range python IndexError:列表索引超出范围python

def reverse_invert(lst):
    inverse_list = []

    for i in lst:
        if isinstance( i, int ):
             inverse_list.append(lst[i])
        #print(inverse_list)       
             print(i)       
        else:
            break
    return inverse_list

Why is it?为什么?

for i in lst:

will iterate the elements of lst .将迭代lst元素

If you want to iterate indexes , use如果要迭代索引,请使用

for i in range(len(lst)):

If you want both the element and the index, use enumerate :如果您想要元素和索引,请使用enumerate

for i, el in enumerate(lst):

You are iterating the elements of list but trying to use the element as index.您正在迭代列表的元素,但尝试使用该元素作为索引。 You should change your code like this:您应该像这样更改代码:

def reverse_invert(lst):
inverse_list = []

for i in lst:
    if isinstance( i, int ):
         inverse_list.append(i) # changed this one.
    #print(inverse_list)       
         print(i)       
    else:
        break
return inverse_list

List comprehension would work fine:列表理解可以正常工作:

a = [1, 'a', 2, 3]

print [d for d in a[::-1] if isinstance(d, int)]

And if you want to reverse it just tiny change would do:如果您想扭转它,只需稍作改动即可:

a = [1, 'a', 2, 3]

print [d for d in a[::-1] if isinstance(d, int)]

Or maybe I missed your point.或者也许我错过了你的观点。

Generally it means that you are providing an index for which a list element does not exist.通常,这意味着您提供的索引不存在列表元素。

Eg, if your list was例如,如果您的清单是

[1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist. [1, 3, 5, 7] ,并且您要求索引 10 处的元素,您将完全超出范围并收到错误,因为只有元素 0 到 3 存在。

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

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