F.L*_*ira 6 python dictionary list
在简历中,我在同一个字典中有两个键,每个键都有对应的列表。
我尝试比较两个列表以检查公共元素和差异元素。这意味着输出 I 将计算有多少元素相同或仅出现在一个键的列表中。
从一开始我就使用文件作为参数插入元素,并在函数中读取它们
def shared(list):
dict_shared = {}
for i in list:
infile = open(i, 'r')
if i not in dict_shared:
dict_shared[i] = []
for line in infile:
dict_shared[spacer].append(record.id)
return dict_shared
Run Code Online (Sandbox Code Playgroud)
现在我被困在试图找到一种方法来比较字典中创建和显示的列表。
dict = {a:[1,2,3,4,5], b:[2,3,4,6]}
Run Code Online (Sandbox Code Playgroud)
我的目的是比较列表,以便在两个文本之间共享行。
a: [1,5]
b: [6]
a-b: [2,3,4]
Run Code Online (Sandbox Code Playgroud)
从现在开始我找不到解决这个问题的方法。有什么建议吗?
您可以使用设置:
d = {'a':[1,2,3,4,5], 'b':[2,3,4,6]}
print(list(set(d['a'])-set(d['b'])))
print(list(set(d['b'])-set(d['a'])))
print(list(set(d['b'])&set(d['a'])))
Run Code Online (Sandbox Code Playgroud)
结果:
[1, 5]
[6]
[2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以通过使用python
诸如union
, difference
, 之类的内置函数来做到这一点intersection
。
注意:这些是 for sets
,您可以将 a 转换list
为set
by
1stset = set(a)
例子:
print(1stset.difference(2ndset))
print(1stset.intersection(2ndset))
print(1stset.union(2ndset))
Run Code Online (Sandbox Code Playgroud)
您可以参考以下链接了解更多信息
https://www.geeksforgeeks.org/python-intersection-two-lists/
https://www.geeksforgeeks.org/python-union-two-lists/
https://www.geeksforgeeks.org/python-difference-two-lists/
具有列表理解的解决方案是:
dictionary = {'a':[1,2,3,4,5], 'b':[2,3,4,6]}
only_in_a = [x for x in dictionary['a'] if not x in dictionary['b']]
only_in_b = [x for x in dictionary['b'] if not x in dictionary['a']]
in_both = [x for x in dictionary['a'] if x in dictionary['b']]
Run Code Online (Sandbox Code Playgroud)
请注意,对于较大的列表,这在复杂性方面并不是特别明智。