[英]Pythonic way to filter list based on index
I am wondering whether there is a pythonic way to perform the following operation on python list. 我想知道是否有一种pythonic的方法可以在python列表上执行以下操作。 The input is : A large python list
demo = [1,3,5,...]
, a input index list index like [0,1]
or [2,3,5]
etc. The intended output for demo = [1,3,5,6]
with index like [0,1]
will be [5,6]
with values in the index list filtered out. 输入为:大型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]
,索引列表中的值将被过滤掉。
A method I can think of is : python list comprehension like [demo[i] for i in index]
gives the opposite [1,3]
and convert demo and [1,3]
to set and apply set difference. 我可以想到的一种方法是:像
[demo[i] for i in index]
一样的python列表[demo[i] for i in index]
给出相反的[1,3]
并转换demo和[1,3]
来设置和应用设置差异。
I am wondering better solution with better performance. 我想知道具有更好性能的更好解决方案。
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)
You can also use filter
您也可以使用
filter
map(lambda x: x[1], filter(lambda x: x[0] not in index, enumerate(demo)))
# or map(operator.itemgetter(1), filter( ... ) )
Or even set operations, with some work.... 甚至设置操作,还有一些工作...。
correct_indexes = set(range(len(demo))) - index
[demo[i] for i in correct_indexes]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.