[英]Efficiently extracting set of unique values from lists within a dictionary
我有一個看起來像這樣的數據結構:
{'A': [2, 3, 5, 6], 'B': [1, 2, 4, 7], 'C': [1, 3, 4, 5, 7], 'D': [1, 4, 5, 6], 'E': [3, 4]}
使用 Python,我需要提取這個:
{1, 2, 3, 4, 5, 6, 7}
因為我需要計算更下游的數學方程式的不同值。
這是我當前的實現,它有效(完整的代碼示例):
from itertools import chain
# Create som mock data for testing
dictionary_with_lists = {'A': [2, 3, 5, 6],
'B': [1, 2, 4, 7],
'C': [1, 3, 4, 5, 7],
'D': [1, 4, 5, 6],
'E': [3, 4]}
print(dictionary_with_lists)
# Output: 'A': [2, 3, 5, 6], 'B': [1, 2, 4, 7], 'C': [1, 3, 4, 5, 7], 'D': [1, 4, 5, 6], 'E': [3, 4]}
# Flatten dictionary to list of lists, discarding the keys
list_of_lists = [dictionary_with_lists[i] for i in dictionary_with_lists]
print(f'list_of_lists: {list_of_lists}')
# Output: list_of_lists: [[2, 3, 5, 6], [1, 2, 4, 7], [1, 3, 4, 5, 7], [1, 4, 5, 6], [3, 4]]
# Use itertools to flatten the list
flat_list = list(chain.from_iterable(list_of_lists))
print(f'flat_list: {flat_list}')
# Output: flat_list: [2, 3, 5, 6, 1, 2, 4, 7, 1, 3, 4, 5, 7, 1, 4, 5, 6, 3, 4]
# Convert list to set to get only unique values
set_of_unique_items = set(flat_list)
print(f'set_of_unique_items: {set_of_unique_items}')
# Output: set_of_unique_items: {1, 2, 3, 4, 5, 6, 7}
雖然這可行,但我懷疑可能有更簡單、更有效的方法。
什么是不降低代碼可讀性的更有效的實現?
我的真實世界詞典包含數十萬或數百萬個任意長度的列表。
一個局外人的觀點:
dict = {'A': [2, 3, 5, 6], 'B': [1, 2, 4, 7], 'C': [1, 3, 4, 5, 7], 'D': [1, 4, 5, 6], 'E': [3, 4]}
S = set()
for L in dict.values():
S = S.union(set(L))
試試這個
from itertools import chain
d = {'A': [2, 3, 5, 6], 'B': [1, 2, 4, 7], 'C': [1, 3, 4, 5, 7], 'D': [1, 4, 5, 6], 'E': [3, 4]}
print(set(chain.from_iterable(d.values())))
Output:
{1, 2, 3, 4, 5, 6, 7}
s = set()
for key in dictionary_with_lists:
for val in dictionary_with_lists[key]:
s.add(val)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.