查找大量列表具有相同元素的列表

时间:2019-07-12 15:35:59

标签: python list set

我有一个列表字典(我也可以设置它们)

mydict = {key1: [s11, s12, ...],
          key2: [s21, s22, ...],
          keyN: [sN1, sN2, ...]}

其中s *是字符串。我想确定哪些键具有等效列表。我了解如何对两个列表(==)或集合(交集)进行成对比较,但是我需要收集所有具有匹配列表的键。例如:

common1 = [key1, key97]         # mydict[key1]==mydict[key97]
common2 = [key3, key42, key51]  # these keys from mydict have equivalent lists

任何有效的Python方法吗?

2 个答案:

答案 0 :(得分:0)

result = {} 
for k,v in mydict.items():
    result.setdefault(tuple(v), []).append(k)

commons = result.values()

答案 1 :(得分:0)

# use sets as values so we don't have to worry about ordering
mydict = {
    '1': {'hi', 'bob'},
    '2': {'hi', 'sally'},
    '3': {'greetings', 'steve'},
    '4': {'sally', 'hi'},
    '5': {'salutations', 'mike'},
    '6': {'salutations', 'mike'},
}

common = []

# get a list of all the keys in mydict
keylist = list(mydict.keys())

# compare each key value to all the subsequent key values.
# if they match, add both keys to the common list
for position, key in enumerate(keylist):
    for key2 in keylist[position+1:]:
        if mydict[key] == mydict[key2]:
            common.append(key)
            common.append(key2)

print(common)