[英]Find minimum number of keys which make each dict unique amongst multiple ones
[英]Find unique elements part of each list amongst unknown number of lists
我正在嘗試為后續問題找到有效的解決方案:
我有許多 x 列表(數量未知),每個列表都有不同但也有重疊的元素。 我想分別找到每個列表和 output 唯一的元素。
例如,如果我有 3 個列表:
a = [1,2,3,4]
b = [2,5,6,7]
c = [3,6,8,9]
這將導致 output (我不是試圖僅查找唯一元素):
a --> [1,4]
b --> [5,7]
c --> [8,9]
假設一個列表是按順序生成的。 我正在考慮使用集合,但相信在生成每個列表時可以解決這個問題。
這是 O(N) 中的一個簡單解決方案,其中 N 是元素的總數。
關鍵思想是計算每個元素在所有列表中出現的次數。 然后,您可以通過僅保留出現一次的元素來過濾每個列表。
from collections import Counter
a = [1,2,3,4]
b = [2,5,6,7]
c = [3,6,8,9]
# Count how many times each elements appear.
counter = Counter()
for l in [a,b,c]:
counter.update(l)
print(counter)
# If an element appears only once, it is an unique element !
for l in [a,b,c]:
print(*filter(lambda x: counter[x]==1, l))
output 是:
Counter({2: 2, 3: 2, 6: 2, 1: 1, 4: 1, 5: 1, 7: 1, 8: 1, 9: 1})
1 4
5 7
8 9
利用
set.difference()
- 返回一個集合,其中包含僅存在於集合 x 中而不存在於集合 y 中的項目:前任。
a = [1,2,3,4]
b = [2,5,6,7]
c = [3,6,8,9]
abc = list(set(a).difference(b).difference(c))
bca = list(set(b).difference(c).difference(a))
cab = list(set(c).difference(a).difference(b))
print(abc)
print(bca)
print(cab)
輸出/輸出:
[1, 4]
[5, 7]
[8, 9]
您可以使用 dict 存儲每個數字被看到的次數,並使用它來生成一個與列表進行比較的集合。 使用 dict 意味着您不需要再次將每個新列表與所有其他列表進行比較(但需要重新定義duplicate_numbers
)。
tracker_dict = dict()
duplicate_numbers = set()
a = [1,2,3,4]
b = [2,5,6,7]
c = [3,6,8,9]
# Get count of all numbers in all lists
all_lists = [a, b, c]
for l in all_lists:
for item in l:
tracker_dict[item] = tracker_dict.get(item, 0) + 1
# Store all duplicate numbers in a set
duplicate_numbers = set([num for num in tracker_dict if tracker_dict[num] > 1])
# Get new lists
new_a = [i for i in a if i not in duplicate_numbers]
# With a new list that is defined afterwards
d = [1, 4, 5, 1]
# Update the tracker_dict and duplicate_numbers set
for item in d:
tracker_dict[item] = tracker_dict.get(item, 0) + 1
duplicate_numbers = set([num for num in tracker_dict if tracker_dict[num] > 1])
new_d = [i for i in a if i not in duplicate_numbers]
# This does not affect previously processed lists however
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.