gpt4 book ai didi

python - 从元组中删除元素时额外的空元素

转载 作者:行者123 更新时间:2023-11-28 21:24:15 25 4
gpt4 key购买 nike

我对以下 python 结果有疑问。假设我有一个元组:

a = ( (1,1), (2,2), (3,3) )

我想删除 (2,2),我正在使用以下代码执行此操作:

 tuple([x for x in a if x != (2,2)])

这很好用,结果是:( (1,1), (3,3) ),正如我所料。

但假设我从 a = ( (1,1), (2,2) )

并使用相同的 tuple() 命令,结果是 ( (1,1), ) 而我希望它是 ((1,1))

简而言之

>>> a = ( (1,1), (2,2), (3,3) )
>>> tuple([x for x in a if x != (2,2)])
((1, 1), (3, 3))
>>> a = ( (1,1), (2,2) )
>>> tuple([x for x in a if x != (2,2)])
((1, 1),)

为什么在第二种情况下使用逗号和空元素?我该如何摆脱它?

谢谢!

最佳答案

Python 在元组只有一个元素的情况下使用尾随逗号:

In [21]: type((1,))
Out[21]: tuple

来自 docs :

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

关于python - 从元组中删除元素时额外的空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224406/

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