避免将重复项插入到Python列表中,并具有理解 [英] Avoid inserting duplicates into Python list with comprehension

查看:140
本文介绍了避免将重复项插入到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]

这篇关于避免将重复项插入到Python列表中,并具有理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆