如何将列表列表转换为python中的一组,以便我可以与其他集进行比较?

时间:2015-05-06 17:43:06

标签: python list set

我有一个列表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进行比较。

3 个答案:

答案 0 :(得分:5)

您需要将内部列表转换为元组,假设每个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>])

答案 1 :(得分:1)

虽然可接受的答案是好的,但是如果您希望进行更简单的比较并且不想处理元组的不变性,则也可以使用老式的字符串比较来尝试它:

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))

答案 2 :(得分:0)

如果marker1.getGeometry()的{​​{1}}中有list of lists,则可以使用此函数将其转换为一个lists中的integer

set

示例:

list

输出:

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)