避免将重复项插入到Python列表中,并具有理解
我有一个字典:
XY_dict = {1: [(12, 55),(13, 55)],
2: [(14, 55),(15, 57)],
3: [(14, 55),(15, 58)],
4: [(14, 55),(16, 55)]}
我想知道哪些键有值元组其中唯一(不存在任何其他键值)。从示例字典中,键1是唯一的,因为(12,55)
或(13,55)
在任何其他字典的关键。通过获取具有共享值的密钥列表,我可以稍后反转结果,并获得唯一的密钥。
I want to find out which keys have values tuples of which are unique (don't present in any other key's value). From the sample dictionary, key 1 is unique because neither (12, 55)
nor (13, 55)
is present in any other dictionary's key. By getting the list of keys with shared values, I can invert the result later on and get the keys that are unique.
我正在使用列表解析获取密钥共享值:
I am using a list comprehension for getting keys with shared values:
keys_shared_values = [k1 for k1,v1 in XY_dict.iteritems()
for k,v in XY_dict.iteritems()
for XY_pair in v
if XY_pair in v1 and k != k1 and k1 not in keys_shared_values]
因此,我得到 [2,2,3,3,4,4]
但我预计重复不会被插入(因为我正在评估键值是否在结果列表中)。我可以通过运行列表(set(shared_values))
来修复,但是想了解我的代码有什么问题。
As a result, I am getting [2, 2, 3, 3, 4, 4]
yet I expect duplicates not to be inserted (since I am evaluating whether the key value is in the result list). I can fix that by running the list(set(shared_values))
, but would like to understand what is wrong with my code.
问题在于,您完成理解之前, keys_shared_values
为空,所以您的 k1不在keys_shared_values
将始终返回 True
。你不能参考当前的理解。你最好的选择是转换为设置
,如您所建议的那样。
The problem is that keys_shared_values
is empty until you complete the comprehension, so your k1 not in keys_shared_values
will always return True
. You cannot refer to the current comprehension. Your best bet is to convert to set
as you already suggested.
你应该将代码更改为循环你想要这个功能:
You should change your code to a loop if you want that functionality:
keys_shared_values = []
for k, v in XY_dict.iteritems():
for k1, v1 in XY_dict.iteritems():
for XY_pair in v:
if XY_pair in v1 and k != k1 and k1 not in keys_shared_values:
keys_shared_values.append(k1)
print keys_shared_values
结果:
[3, 4, 2]