Python: split a list based on a condition?

前端 未结 30 2282
误落风尘
误落风尘 2020-11-22 06:56

What\'s the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:

30条回答
  •  一整个雨季
    2020-11-22 07:06

    images = [f for f in files if f[2].lower() in IMAGE_TYPES]
    anims  = [f for f in files if f not in images]
    

    Nice when the condition is longer, such as in your example. The reader doesn't have to figure out the negative condition and whether it captures all other cases.

提交回复
热议问题