如何将列表列表转换为python中的集合,以便与其他集合进行比较?
我有一个列表如何将列表列表转换为python中的集合,以便与其他集合进行比较?,python,list,set,Python,List,Set,我有一个列表users\u和\u-invests\u-ids\u-list,由我在列表中附加值的循环构成,在python中如下所示: ...[ObjectId('55119e14bf2e4e010d8b48f2')], [ObjectId('54624128bf2e4e5e558b5a52')], [ObjectId('53a6e7bc763f4aa0308b4569')], [ObjectId('55241823bf2e4e59508b494c')]] 当我尝试时: users_wi
users\u和\u-invests\u-ids\u-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'),)])
其结果如下:
#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'),)])
如何获取每个
对象ID
,而不在每个对象周围添加()
。这使我无法将此ID集与其他ID集进行比较。您需要将内部列表转换为元组,假设这些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>,)])
虽然公认的答案是好的,但如果您想要比较简单的东西,并且不想处理元组的不变性,您也可以使用老式的字符串比较:
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))
如果列表
具有列表
的整数
,您可以使用此函数将其转换为设置
的一个列表
:
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))
输出:
nested_list = [[7, 7], [2, 3, 3, 0], [9, 1, 9, 1]]
print(lists_to_list(nested_list))
{0,1,2,3,7,9}