Python for and if on one line

后端 未结 6 2127
情书的邮戳
情书的邮戳 2021-01-31 16:51

I have a issue with python.

I make a simple list:

>>> my_list = [\"one\",\"two\",\"three\"]

I want create a \"single line code

6条回答
  •  忘掉有多难
    2021-01-31 17:28

    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.

    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
    

提交回复
热议问题