Python:根据条件拆分列表? [英] Python: split a list based on a condition?
本文介绍了Python:根据条件拆分列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从美学角度和性能角度来看,根据条件将项目列表拆分为多个列表的最佳方法是什么?相当于:
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:
good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
有没有更优雅的方法来做到这一点?
is there a more elegant way to do this?
更新:这是实际用例,以更好地解释我想要做什么:
Update: here's the actual use case, to better explain what I'm trying to do:
# 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)
这篇关于Python:根据条件拆分列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文