类型(1,)返回int预期的tup

2024-04-26 11:41:10 发布

您现在位置:Python中文网/ 问答频道 /正文

type(1,)
Out[1]: int
a=1,
a
Out[3]: (1,)
type(a)
Out[4]: tuple

我使用的是Python3.6,我希望类型(1,)返回一个元组。在

根据this link

... a tuple with one item is constructed by following a value with a comma...

我错过了什么?在


Tags: 类型byistypewithlinkoutthis
2条回答

问题在于python如何解释函数参数,同时允许后面有“qualityoflife”逗号。函数用括号和逗号分隔的参数调用。当您传递type(1,)时,后面带有逗号的逗号分隔参数与实际元组之间存在歧义。在

一个简单的例子:

def test(x):
    print(x) 

test("hello") #Output: hello
test("hello",) #is also valid, Output: hello

要了解python实际上是如何接受参数的,可以使用^{}函数。在

^{pr2}$

为了明确地确保传递元组作为第一个参数,您应该将其括在括号中并解决歧义。在

^{3}$

它之所以在赋值后起作用,是因为在将值存储为元组时,歧义得到了解决。在

a = 1,
repr(a)
'(1,)'

其他信息

至于尾随逗号何时有用,我们可以参考相关的PEP8部分。在

When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line.

也就是说,永远不要在一行中放多余的尾随逗号。在

#No good
func_with_future_changes_or_variable_args(arg1, arg2=True,)

#Good
func_with_future_changes_or_variable_args(arg1,
                                          arg2=True,
                                          )

我个人在函数发生变化时不会遇到太多问题,但是在维护随时间变化的列表或字典时,尾随的逗号是救命稻草。例如:

FILES = [
    'setup.cfg',
    'tox.ini',
    ]

在这样的列表中添加或删除值只需要像下面这样隔离地更改一行,这样就可以很容易地跟踪版本控制提交。在

 FILES = [
     'setup.cfg',
     'tox.ini',
+    'new_item.txt',
    ]

从文件中:

Tuples may be constructed in a number of ways:

  1. Using a pair of parentheses to denote the empty tuple: ()
  2. Using a trailing comma for a singleton tuple: a, or (a,)
  3. Separating items with commas: a, b, c or (a, b, c)
  4. Using the tuple() built-in:tuple() or tuple(iterable)

根据这一点,下面所有的都是元组。您会注意到,对变量的显式赋值消除了所有歧义:

In [8]: a = ()
In [9]: type(a)
Out[9]: tuple    
In [10]: b = (1,)    
In [11]: type(b)
Out[11]: tuple    
In [12]: b = 1,    
In [13]: type(b)
Out[13]: tuple

当我们看type(1,)时,我们应该记住type()是一个函数,后面的逗号是一个参数分隔符1是第一个参数,它是一个整数,并且在Python中允许使用尾随逗号,这是一个有效的语句,但不太明确。根据official docs for ^{},建议使用内置的isinstance函数进行类型检查,该函数更显式:

^{pr2}$

相关问题 更多 >