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

2023-08-31Python开发问题
0

本文介绍了从元组中删除元素时额外的空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10