python 字典项的交集
假设我有一个像这样的字典:
aDict[1] = '3,4,5,6,7,8'
aDict[5] = '5,6,7,8,9,10,11,12'
aDict[n] = '5,6,77,88'
键是任意的,并且可以有任意数量。我想考虑字典中的每个值。
我想将每个字符串视为逗号分隔值,并找到整个字典的交集(所有字典值共有的元素)。所以在这种情况下答案将是“5,6”。我该怎么做?
Suppose I have a dict like:
aDict[1] = '3,4,5,6,7,8'
aDict[5] = '5,6,7,8,9,10,11,12'
aDict[n] = '5,6,77,88'
The keys are arbitrary, and there could be any number of them. I want to consider every value in the dictionary.
I want to treat each string as comma-separated values, and find the intersection across the entire dictionary (the elements common to all dict values). So in this case the answer would be '5,6'. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,您需要将它们转换为真实的列表。
然后就可以用集合来做交集了。
First of all, you need to convert these to real lists.
Then you can use sets to do the intersection.
Python
Set
非常适合该任务。考虑以下内容(伪代码):Python
Set
s are ideal for that task. Consider the following (pseudo code):由于
set.intersection()
接受任意数量的集合,因此您可以在不使用reduce()
的情况下凑合:请注意,此版本不适用于空 <代码>aDict。
如果您使用的是 Python 3,并且您的字典值是
bytes
对象而不是字符串,只需在b","
处分割,而不是","
>。Since
set.intersection()
accepts any number of sets, you can make do without any use ofreduce()
:Note that this version won't work for an empty
aDict
.If you are using Python 3, and your dictionary values are
bytes
objects rather than strings, just split atb","
instead of","
.