嵌套列表中所有元素的Python集合

问题描述 投票:0回答:1

我试图通过这个函数让嵌套列表中的所有元素以set的形式返回,但发生了错误。

list = [[0,4], [2,4], 5, [[[7,2], 3], 4]]

def setof(list):
  bag = set()
  for item in list:
    try: bag.add(item)
    except TypeError: bag.add(setof(item))
  return bag

print(setof(list))

Errors:
try: bag.add(item)
TypeError: unhashable type: ‘list’
During handling of the above exception, another exception occurred:
print(setof(list))
except TypeError: bag.add(setof(item))
TypeError: unhashable the: ‘set’

有谁知道为什么会出现这种情况,或者如何解决,或者有更好的方法吗?这是我第一次来这里。谢谢!我想让所有的元素都能通过这个函数以set的形式返回,但是出现了错误。

python recursion nested-lists try-except
1个回答
0
投票

bag.add(setof(item)) 是试图将一个集合作为元素添加到 bag,而不是合并套路。使用

bag.update(setof(item))

0
投票

你的问题来自于 set.add(list). 这不是 Python 集合所能接受的。所以,你想把所有的内部列表变成集合。试试这个。

def setof(lst):
    bag = set()
    for item in lst:
        try:
            bag.add(set(item))
        except TypeError:
            bag.add(set([item]))
    return bag
© www.soinside.com 2019 - 2024. All rights reserved.