为什么单个元素元组被解释为python中的那个元素?

2023-08-31Python开发问题
6

本文介绍了为什么单个元素元组被解释为python中的那个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

谁能解释为什么单元素元组在 Python 中被解释为那个元素?

Could anyone explain why single element tuple is interpreted as that element in Python?

他们为什么不将元组 (1,) 打印为 (1)?

Why don't they just print the tuple (1,) as (1)?

请看下面的例子:

>>> (1)
1
>>> ((((1))))
1
>>> print(1,)
1
>>> print((1,))
(1,)

推荐答案

单个元素元组永远不会被视为包含的元素.括号主要用于分组,而不是创建元组;逗号就是这样做的.

A single element tuple is never treated as the contained element. Parentheses are mostly useful for grouping, not for creating tuples; a comma does that.

他们为什么不直接将 (1,) 打印为 (1)?

Why don't they just print (1,) as (1)?

可能是因为打印内置容器类型提供了一种表示形式,可用于通过 重新创建容器对象,例如 eval:

Probably because printing a builtin container type gives a representation that can be used to recreate the container object via , say eval:

__repr__的文档a> 对此提供了一些说明:

The docs for __repr__ provides some clarity on this:

如果可能的话,这应该看起来像一个有效的 Python 表达式可用于重新创建具有相同值的对象

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value

回答您的问题,(1) 只是带有分组括号的整数 1.为了通过其表示重新创建单例元组,它必须打印为 (1,) 这是创建元组的有效语法.

Answering your question, (1) is just integer 1 with a grouping parenthesis. In order to recreate the singleton tuple via its representation, it has to be printed as (1,) which is the valid syntax for creating the tuple.

>>> t = '(1,)'
>>> i = '(1)'
>>> eval(t)
(1,) # tuple
>>> eval(i)
1    # int

这篇关于为什么单个元素元组被解释为python中的那个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

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

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11