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

我试图通过此函数以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’

有谁知道为什么会发生这种情况或如何解决它,或者有更好的方法呢?这是我第一次来。谢谢!

评论
  • 一南
    一南 回复

    Your problem is coming from set.add(list). This is not something Python sets accept. So, you want to turn all the inner lists into sets. Try this:

    def setof(lst):
        bag = set()
        for item in lst:
            try:
                bag.add(set(item))
            except TypeError:
                bag.add(set([item]))
        return bag
    
  • 借个吻
    借个吻 回复

    bag.add(setof(item)) is trying to add a set as an element of bag, not combine the sets. Use

    bag.update(setof(item))