从 Python 中的嵌套列表中获取一个集合

Obtain a set from a nested list in Python

我有一个列表(例如 a = [1, 2, 3, [1, 2, 4]]),我想从其嵌套的最低级别的元素创建一个集合(在前面的示例中,以获得 setA = {1, 2, 3, 4})。

运行 set(a) 给我错误:

TypeError: unhashable type: 'list'

我应该怎么做才能获得这样的一套?

您必须首先展平不规则嵌套的列表。以下是 2 个解决方案,可以处理任何深度、不规则嵌套的列表。

使用集合

尝试使用集合来展平 irregular deep nested list -

import collections

def flatten(x):
    if isinstance(x, collections.Iterable):
        return [a for i in x for a in flatten(i)]
    else:
        return [x]
    
a = [1, 2, 3, [1, [2, 4]]] #Irregular deep nested list
out = set(flatten(a))
out
{1, 2, 3, 4}

更多详情here


使用递归

对于嵌套较深的列表,可以使用recursion -

def flatten(S):
    if S == []:
        return S
    if isinstance(S[0], list):
        return flatten(S[0]) + flatten(S[1:])
    return S[:1] + flatten(S[1:])

a = [1, 2, 3, [1, [2, 4]]] #Irregular deep nested list
out = set(flatten(a))
out
{1, 2, 3, 4}

更多详情here


单行递归

如果像我一样,你更喜欢使用单行代码,试试这个带递归的 lambda 函数 -

f = lambda *n: (e for a in n for e in (f(*a) if isinstance(a, (tuple, list)) else (a,)))

out = set(f(a))
out
{1, 2, 3, 4}

更多详情here

这是我的建议。它使用递归并适用于任何级别的嵌套结构:

import collections

def getset(l):
    res=set()
    for i in l:
        if isinstance(i, collections.Iterable):
            res=res.union(getset(i))
        else:
            res.add(i)
    return res

getset(a)
#{1,2,3,4}

getset([1, 2, 3, [4, 5, [10, 20, [100, 200]]], [12, 14, [16, 18]]])
#{1, 2, 3, 4, 5, 100, 200, 10, 12, 14, 16, 18, 20}