在python中使用哈希表(字典)查找对称对

时间:2019-06-02 07:46:06

标签: python list dictionary tuples hashtable

例如,我正在尝试获取没有重复的对称对,

L=[(1,3), (2,6), (3,5), (4,7), (5,3), (6,2), (3,4),(4,3)]

,我想像[(2,6), (3,5), (3,4)],找到对称对。

这是我的完整代码,

L=[(1,3), (2,6), (3,5), (4,7), (5,3), (6,2), (3,4),(4,3)]

def find_symmetric_pairs(L):
    temp = {}
    temp_list = []
    for i in L:
        key, value = i
        for j in L:
            key_j, value_j = j
            if key == value_j and value == key_j:
                temp_list.append(tuple((key,value)))
    return temp_list

而且,我正在尝试通过使用python哈希表实现此功能,如何使用哈希表? 输出看起来像这样

[(2, 6), (3, 5), (5, 3), (6, 2), (3, 4), (4, 3)] 但我想像我最初告诉你的那样显示输出... [(2,6), (3,5), (3,4)]

3 个答案:

答案 0 :(得分:2)

您只需要添加检查以查看对称对是否已添加到您的结果中,

AuthorizationRequestRepository

输出将为

L=[(1,3), (2,6), (3,5), (4,7), (5,3), (6,2), (3,4),(4,3)]

res = set()

#Convert the list to a set
L = set(L)
# Iterate through the set
for t in L:
    # If the a tuple is present , and the reversed tuple is not in the result set already
    if (t[1], t[0]) in L and (t[1], t[0]) not in res:
        # Add it to result set
        res.add(t)

print(res)

另一种方法是对元组重新排序,以使第一个元素大然后第二个,并通过collections.Counter对元组进行计数。计数为2的元素将是对称对

{(2, 6), (4, 3), (3, 5)}

输出将为

from collections import Counter

L=[(1,3), (2,6), (3,5), (4,7), (5,3), (6,2), (3,4),(4,3)]

#reorder tuple so that first element is bigger then second
L = [(t[1], t[0]) if t[0] < t[1] else t for t in L]

#Make a counter 
c = Counter(L)

#Count elements with count 2
res = [key for key, value in c.items() if value == 2]
print(res)

答案 1 :(得分:2)

Python中没有这样的哈希表,但是您可以使用集合。以下内容将原始的元组set(L)与一组反向的元组{(y, x) for x, y in L}结合在一起。稍后,它只保留第一个元素较小的对:

pairs = set(L) & {(y, x) for x, y in L}
{(x,y) for x,y in pairs if x < y}
#{(2, 6), (3, 4), (3, 5)}

答案 2 :(得分:1)

如果您想忽略订单,可以使用一套。具体来说,frozenset将允许您散列并因此使用Counter

from collections import Counter
L_set_counter = Counter(map(frozenset, set(L)))

现在L_set_counter包含:

Counter({frozenset({2, 6}): 2, frozenset({3, 5}): 2, frozenset({3, 4}): 2, frozenset({1, 3}): 1, frozenset({4, 7}): 1})

并查找重复项(v==2使其更具体,这更通用):

dups = {k for k, v in L_set_counter.items() if v > 1}

现在dups包含:

{frozenset({3, 4}), frozenset({3, 5}), frozenset({2, 6})}