相关疑难解决方法(0)

为什么list.append在布尔上下文中求值为false?

是否有理由进行list.append评估?或者只是在成功发挥作用时返回0的C约定?

>>> u = []
>>> not u.append(6)
True
Run Code Online (Sandbox Code Playgroud)

python list

33
推荐指数
4
解决办法
8037
查看次数

在setdefault之后附加到字典中的列表

我有下面的代码,我试图在输入中每次出现一个元素的哈希值时附加1.

def test(Ar):
    hash_table = {}
    for elem in Ar:
        if elem not in hash_table:
            hash_table.setdefault(elem,[]).append(1)
        else:
            hash_table[elem] = hash_table[elem].append(1)
    print(hash_table)

Ar = (1,2,3,4,5,1,2)
test(Ar)
Run Code Online (Sandbox Code Playgroud)

输出:

{1: None, 2: None, 3: [1], 4: [1], 5: [1]}
Run Code Online (Sandbox Code Playgroud)

预期产出:

{1: [1,1], 2: [1,1], 3: [1], 4: [1], 5: [1]}
Run Code Online (Sandbox Code Playgroud)

我很困惑为什么没有进入追加.请解释发生了什么.

注意:

在键入其他部分时,

hash_table[elem] = hash_table[elem].append(1) # the append() was not suggested at all by the IDE. I forcibly put it, hoping things will work.
Run Code Online (Sandbox Code Playgroud)

python dictionary list append

3
推荐指数
1
解决办法
5561
查看次数

标签 统计

list ×2

python ×2

append ×1

dictionary ×1