小编家宁张*_*家宁张的帖子

无法将列表转换为集合,引发“unhashable type: 'list'”错误

所以我试图找到一个列表的所有子列表,这就是我现在所拥有的。我是 Python 新手,我不明白为什么“Q3_ans=set(ans)”会引发错误。我已经尝试将列表转换为之前设置的并且它有效。

def f2(seq):
    '''
    This is the base case of the recursion from function all_sublists
    '''
    assert len(seq)==2
    assert isinstance(x,list)
    a,b=seq
    return [[a],[b],[a,b]]


def all_sublists(x):
    '''
    This function will generate all of the sublists of a list, not including the empty one, using recursion
    '''
    assert isinstance(x,list)
    ans=[]
    for i in range(0,len(x)-1):
        for j in range(1,len(x)):
            temp=[x[i],x[j]]
            temp=[f2(temp)]
            ans.extend(temp)
    Q3_ans=set(ans) 
    return Q3_ans
Run Code Online (Sandbox Code Playgroud)

这是我运行代码时的错误 y=[1,2,3,4,5]

all_sublists(y)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-108-f8b1bb0a7001> in <module>
----> 1 all_sublists(y) …
Run Code Online (Sandbox Code Playgroud)

python list set python-3.x

6
推荐指数
1
解决办法
6313
查看次数

标签 统计

list ×1

python ×1

python-3.x ×1

set ×1