从元组中删除元素时额外的空元素
问题描述
我对以下 python 结果有疑问.假设我有一个元组:
I have a question about the following python outcome. Suppose I have a tuple :
a = ( (1,1), (2,2), (3,3) )
我想删除 (2,2)
,我正在使用以下代码:
I want to remove (2,2)
, and I'm doing this with the following code:
tuple([x for x in a if x != (2,2)])
这很好用,结果是:( (1,1), (3,3) )
,正如我所料.
This works fine, the result is: ( (1,1), (3,3) )
, just as I expect.
但假设我从 a = ( (1,1), (2,2) )
并使用相同的 tuple() 命令,结果是 ( (1,1), )
而我希望它是 ((1,1))
and use the same tuple() command, the result is ( (1,1), )
while I would expect it to be ((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),)
为什么在第二种情况下逗号和空元素?我该如何摆脱它?
Why the comma and empty element in the second case? And how do I get rid of it?
谢谢!
解决方案
如果元组只有一个元素,Python 使用尾随逗号:
Python uses a trailing comma in case a tuple has only one element:
In [21]: type((1,))
Out[21]: tuple
来自 文档:
一个特殊的问题是包含 0 或 1 的元组的构造items:语法有一些额外的怪癖来适应这些.空的元组由一对空括号构成;一个元组一个项目是通过在一个带有逗号的值后面构造的(它不是足以将单个值括在括号中).
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',)
相关文章