【问题标题】:How to convert list of lists to a set in python so I can compare to other sets?python - 如何将列表列表转换为python中的集合,以便与其他集合进行比较?
【发布时间】:2015-07-17 00:22:18
【问题描述】:

我有一个列表users_with_invites_ids_list,由循环形成,我将值附加到列表中,在 python 中如下所示:

...[ObjectId('55119e14bf2e4e010d8b48f2')], [ObjectId('54624128bf2e4e5e558b5a52')], [ObjectId('53a6e7bc763f4aa0308b4569')], [ObjectId('55241823bf2e4e59508b494c')]]

当我尝试时:

    users_with_invites_ids_set = set(users_with_invites_ids_list)

我明白了:

TypeError: unhashable type: 'list'

如何将此列表列表转换为集合?

编辑

根据回答,我做了以下事情:

#convert list to set
first_tuple_list = [tuple(lst) for lst in users_with_invites_ids_list]
users_with_invites_ids_set = set(first_tuple_list)

产生以下结果:

 (ObjectId('542ac5a6763f4a82188b4a51'),), (ObjectId('54496fe6bf2e4efe348bd344'),), (ObjectId('54c96339bf2e4ee62c8b48e0'),)])

如何在没有() 的情况下获得每个ObjectId。它使我无法将此集合与其他 ID 集合进行比较。

【问题讨论】:

    标签: python list set


    【解决方案1】:

    您需要将内部列表转换为元组,假设每个 ObjectId('55119e14bf2e4e010d8b48f2') 都是可散列的:

    users_with_invites_ids_set = set(tuple(x) for x in users_with_invites_ids_list)
    

    工作示例:

    >>> class ObjectId(object):
    ...   def __init__(self, v):
    ...     self.v = v
    ... 
    >>> list_of_lists = [[ObjectId('55119e14bf2e4e010d8b48f2')], [ObjectId('54624128bf2e4e5e558b5a52')], [ObjectId('53a6e7bc763f4aa0308b4569')], [ObjectId('55241823bf2e4e59508b494c')]]
    >>> set(tuple(x) for x in list_of_lists)
    set([(<__main__.ObjectId object at 0x7f71483cfc50>,), (<__main__.ObjectId object at 0x7f71483cfd10>,), (<__main__.ObjectId object at 0x7f71483cfcd0>,), (<__main__.ObjectId object at 0x7f71483cfc90>,)])
    

    如果您想单独创建 ObjectId 的集合,您可以这样做:

    >>> set(x for lst in list_of_lists for x in lst)
    set([<__main__.ObjectId object at 0x7f71483cfb10>, <__main__.ObjectId object at 0x7f71483db050>, <__main__.ObjectId object at 0x7f71483cfad0>, <__main__.ObjectId object at 0x7f71483cfd50>])
    

    【讨论】:

      【解决方案2】:

      如果list of listslistsinteger,您可以使用此函数将其转换为setlist 之一:

      outer_list = [] 
      def lists_to_list(nested_lists): 
          for el in nested_lists: 
              if type(el) == list: 
                  lists_to_list(el) 
              else: 
                  outer_list.append(el)
          return set(outer_list)
      

      示例:

      nested_list = [[7, 7], [2, 3, 3, 0], [9, 1, 9, 1]]
      print(lists_to_list(nested_list))
      

      输出:

      {0, 1, 2, 3, 7, 9}

      【讨论】:

        【解决方案3】:

        虽然公认的答案很好,但如果您想要更简单的比较并且不想处理元组的不变性,您也可以尝试使用良好的老式字符串比较:

        list1 = [[], [60], [95], [60, 95]]
        list2 = [[], [95], [60], [60, 95]]
        print(set(str(x) for x in list1) == set(str(x) for x in list2))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-16
          • 2017-01-01
          • 2011-08-31
          • 2011-09-29
          • 1970-01-01
          • 1970-01-01
          • 2017-02-27
          • 1970-01-01
          相关资源
          最近更新 更多