Python for and if on one line

后端 未结 6 2075
情书的邮戳
情书的邮戳 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:27

    In python3 the variable i will be out of scope when you try to print it.

    To get the value you want you should store the result of your operation inside a new variable:

    my_list = ["one","two","three"]
    result=[(i) for i in my_list if i=="two"]
    print(result)
    

    you will then the following output

    ['two']
    

提交回复
热议问题