gpt4 book ai didi

python - 逗号在增强列表分配中的用法是什么?

转载 作者:行者123 更新时间:2023-12-02 04:38:30 33 4
gpt4 key购买 nike

我看到了这样的 Python 语法:

l = []
l += 8,
l的结果是 [8] , 显然是 8 后面的逗号更改整数可迭代,以便它可以添加一个列表。
没有逗号:
l = []
l += 8
它将有 TypeError: 'int' object is not iterable 的错误
我在网上搜索,但没有找到这种语法的任何有用的解释。是否有任何文档可以引用 Python 中的逗号或任何其他逗号用法?

最佳答案

这是旧的,但我最近试图理解相同的语法,这是我发现的:

l=[]
l+=8,

这段代码有两部分 -
  • 单个值后跟一个逗号创建一个带有单个值的元组(一个可迭代的),所以,
    l+=8,    ## implies l+=(8,)
  • 增广赋值运算符 +=调用就地方法 __iadd__并实现为 sq_inplace_concat为列表l ,解释列表和元组的串联。引自 PEP 203: Augmented Assignments :

    Some special casing exists to account for the case of + and *, which have a special meaning for sequences: for +, sequence concatenation, no coercion what so ever is done if a C type defines sq_concat or sq_inplace_concat.



    本质上,该运算符的行为类似于 extend()列表的函数并通过使用以下可迭代对象(在本例中为元组)扩展它来就地修改列表。
    l=[]     
    l+=8, ## eventually implies l.extend((8,))
    print(l) ## [8]

  • list.extend() 函数只接受可迭代对象的事实解释了错误 TypeError: 'int' object is not iterable .

    关于python - 逗号在增强列表分配中的用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732771/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com