如何根据条件拆分列表?

2022-02-20 00:00:00 python list

问题描述

根据条件将项目列表拆分为多个列表的最佳方式是什么,无论从美学角度还是从性能角度来看都是如此?等同于:

good = [x for x in mylist if x in goodvals]
bad  = [x for x in mylist if x not in goodvals]

有没有更优雅的方法来做这件事?

这里是实际使用案例,为了更好地解释我正在尝试做的事情:

# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims  = [f for f in files if f[2].lower() not in IMAGE_TYPES]

解决方案

good, bad = [], []
for x in mylist:
    (bad, good)[x in goodvals].append(x)

相关文章