【问题标题】:Python: Convert list of sets to dictionary with indexesPython:将集合列表转换为带有索引的字典
【发布时间】:2020-08-07 17:52:48
【问题描述】:

我正在尝试转换以下列表:

listOfSets = [{"dog", "cat", "bird"}, {"blue", "yellow", "white"}]

到像这样的字典:

dictt =  {"dog" : 0, "cat" : 0, "bird" : 0, "blue" : 1,  "yellow" : 1, "white" : 1}}

我在这里尝试了其他帖子的建议,但没有成功, 例如,我尝试使用 enumerate 并得到以下错误:

Type error Unhashable type:set

当然要寻找最清晰和优雅的方式来实现它。

谢谢。

【问题讨论】:

    标签: python list python-2.7 dictionary set


    【解决方案1】:

    您可能正在迭代集合,而不是集合的元素,请执行以下操作:

    listOfSets = [{"dog", "cat", "bird"}, {"blue", "yellow", "white"}]
    
    result = {si : i for i, s in enumerate(listOfSets) for si in s}
    print(result)
    

    输出

    {'bird': 0, 'cat': 0, 'dog': 0, 'blue': 1, 'white': 1, 'yellow': 1}
    

    上面的dictionary comprehension等价于:

    listOfSets = [{"dog", "cat", "bird"}, {"blue", "yellow", "white"}]
    
    result = {}
    for i, s in enumerate(listOfSets):
        for si in s:
            result[si] = i
    
    print(result)
    

    【讨论】:

      【解决方案2】:

      你也可以试试这样的

      listOfSets = [{"dog", "cat", "bird"}, {"blue", "yellow", "white"}]
      
      >>> dict(list((s,i) for i, j in enumerate(listOfSets) for s in j))
      {'cat': 0, 'bird': 0, 'dog': 0, 'white': 1, 'yellow': 1, 'blue': 1}
      

      【讨论】:

        猜你喜欢
        • 2022-10-06
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        • 1970-01-01
        • 2021-02-04
        • 1970-01-01
        • 1970-01-01
        • 2015-07-23
        相关资源
        最近更新 更多