如何解决从字典中的列表中有效地提取一组唯一值
我有一个看起来像这样的数据结构:
{'A': [2,3,5,6],'B': [1,2,4,7],'C': [1,'D': [1,'E': [3,4]}
使用Python,我需要提取以下内容:
{1,6,7}
因为我需要对下游的数学方程计算不同的值。
这是我当前的实现,可以正常工作(完整的代码示例):
from itertools import chain
# Create som mock data for testing
dictionary_with_lists = {'A': [2,4]}
print(dictionary_with_lists)
# Output: 'A': [2,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,[1,[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,1,7,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,7}
虽然可行,但我怀疑可能会有一种更简单,更有效的方法。
在不降低代码可读性的情况下,什么是更有效的实现?
我的现实世界词典包含成千上万个任意长度的列表。
解决方法
一个人的观点:
https
,
尝试一下
from itertools import chain
d = {'A': [2,3,5,6],'B': [1,2,4,7],'C': [1,'D': [1,'E': [3,4]}
print(set(chain.from_iterable(d.values())))
输出:
{1,6,7}
,
s = set()
for key in dictionary_with_lists:
for val in dictionary_with_lists[key]:
s.add(val)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。