简体   繁体   English

列表理解内的条件中没有索引错误

[英]No Index Error in Conditional within List Comprehension

When I run the code: 当我运行代码时:

mylist = []
mylist[1]

I get IndexError: list index out of range. 我得到IndexError:列表索引超出范围。 This makes sense to me. 这对我来说很有意义。 But when I run the following code: 但是当我运行以下代码时:

mylist = []
newlist = [x for x in mylist if mylist[1] == 'mystring']
print(newlist)

I don't get an index error, it just prints an empty list. 我没有索引错误,它只是打印一个空列表。 This is what I want the code to do, but I don't understand why it doesn't give me and IndexError. 这就是我想要的代码,但是我不明白为什么它没有给我和IndexError。 From what I can tell, this only occurs when the the list is empty, otherwise you could get an index error if you indexed the list out of range. 据我所知,这只会在列表为空时发生,否则,如果索引超出范围,则可能会出现索引错误。 For example: 例如:

mylist = ['string']
newlist = [x for x in mylist if mylist[1] == 'mystring']

returns the IndexError I would expect it to return. 返回IndexError我希望它会返回。

If anyone could help explain why if you have a conditional statement specifying an index of an empty list in a list comprehension, you don't get an index error, that would be fantastic. 如果有人可以帮助解释为什么如果您有一个条件语句在列表理解中指定一个空列表的索引,那么您不会得到索引错误,那就太好了。

This has nothing to do with conditionals and comprehensions. 这与条件和理解无关。 It's simply the fact that iterating over an empty sequence or collection produces no iterations. 只是事实是,对空序列或集合进行迭代不会产生任何迭代。 Notice how the following code block doesn't produce an error in the for loop, even though x is not defined: 请注意,即使未定义x ,以下代码块也不会在for循环中产生错误:

>>> a = 0
>>> for i in []:
...     x = x + 2
...
>>> a
0
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Since mylist is already empty, for x in mylist will never iterate so if check will never be executed. 由于mylist已经为空,因此for x in mylist永远不会进行迭代,因此if check永远不会执行。 Same thing applies for normal for loops as well: 同样的情况也适用于普通的for循环:

>>> mylist = []
>>> for x in mylist:
...     print "second item", mylist[1]

# will print nothing

[x for x in mylist if mylist[1] == 'mystring'] ,对于每个迭代都执行if mylist[1] == 'mystring'子句-但由于mylist为空,因此迭代次数为零,因此它根本没有执行。

The expression if mylist[1] == 'mystring' is evaluated for each value in mylist . if mylist[1] == 'mystring'则对mylist每个值求表达式。

As mylist is empty, the expression is never evaluated. 由于mylist为空,因此永远不会对表达式求值。

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

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