understanding “item for item in list_a if …” PYTHON

后端 未结 4 1349
北海茫月
北海茫月 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:33

    It might be clearer if you split it into three parts:

    1. Take item;
    2. From for item in list;
    3. Where item not in list_b.

    The reason the list comprehension syntax is like this is firstly because that reflects the expanded version:

    for item in list: # 2.
        if item not in list_b: # 3.
            new_list.append(item) # 1.
    

    and also because you don't necessarily want just item, for example:

    new = [x ** 2 for x in old if not x % 2]
    

    will create a new list with the squares of all even numbers in old.

提交回复
热议问题