understanding “item for item in list_a if …” PYTHON

后端 未结 4 1344
北海茫月
北海茫月 2021-02-04 21:48

I\'ve seen the following code many times, and I know it\'s the solution to my problems, but I\'m really struggling to understand HOW it works. The code in particular is:

4条回答
  •  时光说笑
    2021-02-04 22:49

    You are building a list by looping through(and filtering) another list

    The first item is the thing you are putting into your result list

    You can also do stuff to the element such as

    [i*2 for i in range(6)]
    

    The output will be:

     [0, 2, 4, 6, 8, 10]
    

    Essentially the first "item" lets you control what you put into your result list

提交回复
热议问题