【问题标题】:Find which lists have same elements for large number of lists查找哪些列表具有大量列表的相同元素
【发布时间】:2019-07-12 15:35:59
【问题描述】:

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

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 中有什么有效的方法吗?

【问题讨论】:

  • 这是作业问题。你必须展示你到目前为止所做的尝试。
  • 不,不是作业。
  • 列表中元素的顺序听起来并不重要——对吗?

标签: python list set


【解决方案1】:
result = {} 
for k,v in mydict.items():
    result.setdefault(tuple(v), []).append(k)

commons = result.values()

【讨论】:

    【解决方案2】:
    # 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)
    

    【讨论】:

    • 感谢您的贡献。查看 Michael Ekoka 的优雅解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多