我有几个列表具有相同数量的条目(每个条目指定一个对象属性):
属性a=[545,656,5.4,33]
属性_b=[1.2,1.3,2.3,0.3]
...
并使用相同长度的标志列出
好的对象=[真,假,假,真]
(很容易用等效索引列表替代:
良好的索引=[0,3]
生成新列表的最简单方法是什么?property\u asel,property\u bsel,…这些列表只包含True条目或索引指示的值
属性\u asel=[545,33]
属性_bsel=[1.2,0.3]
您可以使用列表理解:
property\u asel=[val for is\u good,val in zip(good\u objects,property\u a)if is\u good]
或
property\u asel=[property\u a[i]表示良好索引中的i]
后者的速度更快,因为好的_索引比属性_a的长度要少,假设好的_索引是预先计算的,而不是动态生成的
Edit:第一个选项相当于自Python 2.7/3.1以来可用的itertools.compress。请参见@Gary Kerr的答案
property\u asel=list(itertools.compress(property\u a,good\u对象))