proper use of list comprehensions - python

后端 未结 5 921
予麋鹿
予麋鹿 2020-12-10 04:32

Normally, list comprehensions are used to derive a new list from an existing list. Eg:

>>> a = [1, 2, 3, 4, 5]
>>> [i for i in a if i >          


        
5条回答
  •  一个人的身影
    2020-12-10 05:19

    Only use list comprehensions if you plan to use the created list. Otherwise you create it just for the GC to throw it again without ever being used.

    So instead of [b.append(i) for i in a] you should use a proper for loop:

    for i in a:
        b.append(i)
    

    Another solution would be through a generator expression:

    b += (i for i in a)
    

    However, if you want to append the whole list, you can simply do

    b += a
    

    And if you just need to apply a function to the elements before adding them to the list, you can always use map:

    b += map(somefunc, a)
    

提交回复
热议问题