繁体   English   中英

基于索引的Python方式过滤列表

[英]Pythonic way to filter list based on index

我想知道是否有一种pythonic的方法可以在python列表上执行以下操作。 输入为:大型python列表demo = [1,3,5,...] ,输入索引列表索引,例如[0,1][2,3,5][2,3,5]的预期输出demo = [1,3,5,6]索引为[0,1] demo = [1,3,5,6]将为[5,6] ,索引列表中的值将被过滤掉。

我可以想到的一种方法是:像[demo[i] for i in index]一样的python列表[demo[i] for i in index]给出相反的[1,3]并转换demo和[1,3]来设置和应用设置差异。

我想知道具有更好性能的更好解决方案。

demo = [1,3,5,7,9,11,13]
index = {2,3,5}
[value for i, value in enumerate(demo) if i not in index]
# [1, 3, 9, 13]
# Note that you can use a generator expression for a large list that you don't
#   require to be in memory all at once, e.g.
# (value for i,value in enumerate(demo) if i not in index)

您也可以使用filter

map(lambda x: x[1], filter(lambda x: x[0] not in index, enumerate(demo)))
# or map(operator.itemgetter(1), filter( ... ) )

甚至设置操作,还有一些工作...。

correct_indexes = set(range(len(demo))) - index
[demo[i] for i in correct_indexes]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM