Python for and if在一行上 [英] Python for and if on one line
问题描述
我在使用python时遇到问题.
I have a issue with python.
我列出一个简单的列表:
I make a simple list:
>>> my_list = ["one","two","three"]
我想创建一个单行代码"来查找字符串.
I want create a "single line code" for find a string.
例如,我有以下代码:
>>> [(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?
推荐答案
您正在通过使用列表理解来生成过滤列表. i
仍绑定到该列表的每个元素,并且最后一个元素仍然是'three'
,即使随后已从要生成的列表中将其滤除.
You are producing a filtered list by 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.
您不应使用列表推导来挑选一个元素.只需使用for
循环,然后使用break
结束循环即可:
You should not use a list comprehension to pick out one element. Just use a for
loop, and break
to end it:
for elem in my_list:
if elem == 'two':
break
如果您必须使用单行代码(这与Python的哲学相反,在该哲学中,可读性很重要),请使用
If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next()
function and a generator expression:
i = next((elem for elem in my_list if elem == 'two'), None)
,如果没有这样的匹配元素,则会将i
设置为None
.
which will set i
to None
if there is no such matching element.
上面的过滤器不是那么有用;您实际上是在测试值'two'
是否在列表中.您可以为此使用in
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:
elem = 'two' if 'two' in my_list else None
这篇关于Python for and if在一行上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!