簡體   English   中英

同時過濾兩個列表

[英]Filtering two lists simultaneously

我有三個清單:

del_ids = [2, 4]
ids = [3, 2, 4, 1]
other = ['a', 'b', 'c', 'd']

我的目標是刪除del_ids ,結果是

ids = [3, 1]
other = ['a', 'd']

我試圖為要保留的元素做一個掩碼( mask = [id not in del_ids for id in ids] ),我計划在兩個列表上應用這個掩碼。

但我覺得這不是一個pythonic的解決方案。 你能告訴我我怎樣才能做得更好嗎?

再次壓縮、過濾和解壓:

ids, other = zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids))

zip()調用將每個id與相應的other元素配對,生成器表達式過濾掉id列在del_ids任何對,然后zip(*..)然后再次將剩余的對梳理成單獨的列表。

演示:

>>> del_ids = [2, 4]
>>> ids = [3, 2, 4, 1]
>>> other = ['a', 'b', 'c', 'd']
>>> zip(*((id, other) for id, other in zip(ids, other) if id not in del_ids))
[(3, 1), ('a', 'd')]

壓縮、過濾、解壓:

ids, other = zip(*filter(lambda (id,_): not id in del_ids, zip(ids, other)))

為了避免學習棘手的語法,分兩步完成。

other = [o for my_id, o in zip(ids, other) if my_id not in del_ids]
ids = [my_id for my_id in ids if my_id not in del_ids]

缺點
您必須以正確的順序執行語句,因此如果由於某種原因順序更改,則存在錯誤的風險。

優勢
它很簡單,所以下次你想這樣做時就不必搜索 Stackoverflow。

轉換為熊貓數據框並應用掩碼:

del_ids = [2, 4]
ids = [3, 2, 4, 1]
other = ['a', 'b', 'c', 'd']
df = pd.DataFrame({'ids':ids,'other':other})
df = df[~df.ids.isin(del_ids)]
ids = df['ids'].tolist()
other = df['other'].tolist()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM