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

extra empty element when removing an element from a tuple(从元组中删除元素时额外的空元素)
本文介绍了从元组中删除元素时额外的空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下 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',)

这篇关于从元组中删除元素时额外的空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)