Python for 和 if 在一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32580489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python for and if on one line
提问by rostonik
I have a issue with python.
我有 python 的问题。
I make a simple list:
我列一个简单的清单:
>>> my_list = ["one","two","three"]
I want create a "single line code" for find a string.
我想创建一个“单行代码”来查找字符串。
for example, I have this code:
例如,我有这个代码:
>>> [(i) for i in my_list if i=="two"]
['two']
But when I watch the variable is wrong (I find the last value of my list):
但是当我看到变量是错误的(我找到了列表的最后一个值):
>>> print i
three
Why does my variable contain the last element and not the element that I want to find?
为什么我的变量包含最后一个元素而不是我想要查找的元素?
采纳答案by Martijn Pieters
You are producing a filtered listby using a list comprehension. i
is still being bound to each and every element of that list, and the last element is still 'three'
, even if it was subsequently filtered out from the list being produced.
您正在使用列表理解生成过滤列表。i
仍然绑定到该列表的每个元素,并且最后一个元素仍然是'three'
,即使它随后从正在生成的列表中过滤掉。
You should not use a list comprehension to pick out one element. Just use a for
loop, and break
to end it:
你不应该使用列表推导来挑选一个元素。只需使用一个for
循环,并break
结束它:
for elem in my_list:
if elem == 'two':
break
If you musthave a one-liner (which would be counter to Python's philosophy, where readability matters), use the next()
functionand a generator expression:
如果您必须有一个单行(这与 Python 的哲学背道而驰,可读性很重要),请使用next()
函数和生成器表达式:
i = next((elem for elem in my_list if elem == 'two'), None)
which will set i
to None
if there is no such matching element.
如果没有这样的匹配元素,它将设置i
为None
。
The above is not that useful a filter; your are essentially testing if the value 'two'
is in the list. You can use in
for that:
上面的过滤器不是那么有用;您本质上'two'
是在测试该值是否在列表中。你可以使用in
:
elem = 'two' if 'two' in my_list else None
回答by Cong Ma
When you perform
当你执行
>>> [(i) for i in my_list if i=="two"]
i
is iterated through the list my_list
. As the list comprehension finishes evaluation, i
is assigned to the last item in iteration, which is "three"
.
i
遍历列表my_list
。当列表理解完成评估时,i
被分配给迭代中的最后一项,即"three"
。
回答by desiato
In list comprehension the loop variable i becomes global. After the iteration in the for loop it is a reference to the last element in your list.
在列表理解中,循环变量 i 成为全局变量。在 for 循环中迭代之后,它是对列表中最后一个元素的引用。
If you want all matches then assign the list to a variable:
如果您想要所有匹配项,则将列表分配给一个变量:
filtered = [ i for i in my_list if i=='two']
If you want only the first match you could use a function generator
如果你只想要第一场比赛,你可以使用函数生成器
try:
m = next( i for i in my_list if i=='two' )
except StopIteration:
m = None