[英]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.