[英]Python iterating through a nested list to check if the element appears more than 3 times
我在 Python 中有 2 個列表。
列表 1 是一個集合,因此只有唯一的元素: ['bird','elephant,'','123','test..,'hi']
列表 2 是一個嵌套列表: [['bird','123',43'],['','bird','33],['123','hello','bird']]
我想檢查列表 1 中的元素是否在嵌套列表中的任何位置出現超過 3 次。 如果它確實出現 3 次或更多次,我想從嵌套列表中刪除該元素。
在上面顯示的示例中,應從所有 3 個嵌套列表的列表 2 中刪除元素'bird'
。 我之后的輸出是: [['123',43'],['','33],['123','hello']]
我還想創建一個單獨的已刪除項目列表。
請有人可以分享我如何處理這個問題嗎?
您將必須對元素進行計數才能知道項目是否出現了 3 次以上。 為了提高效率,您應該避免在循環中使用count()
並且只執行一次。
一旦你有了計數,你可以用類似的東西過濾你的列表:
from collections import Counter
from itertools import chain
s = set(['bird','elephant','','123','test','hi'])
list2 = [['bird','123','43'],['','bird','33'],['123','hello','bird']]
# get counts of all the items that are in s and list2
counts = Counter(word for word in chain.from_iterable(list2) if word in s)
# create lists filter by count < 3
newList = [[item for item in sublist if counts.get(item, 0) < 3] for sublist in list2]
# [['123', '43'], ['', '33'], ['123', 'hello']]
要滿足所有條件:
from collections import Counter
lst1 = ['bird', 'elephant', '', '123', 'test..', 'hi']
lst2 = [['bird', '123', '43'], ['', 'bird', '33'], ['123', 'hello', 'bird']]
filter_items = {k for k, v in Counter(j for i in lst2 for j in i).items() if v >= 3} & set(lst1)
result, removed_items = [], []
for sub_l in lst2:
result.append([])
for i in sub_l:
if i in filter_items:
removed_items.append(i)
else:
result[-1].append(i)
print(result) # [['123', '43'], ['', '33'], ['123', 'hello']]
print(removed_items) # ['bird', 'bird', 'bird']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.