[英]Tuple comparison in function
I am wondering why my comparison returns False
and not True
although 'a' == 'a'
.我想知道为什么我的比较返回
False
而不是True
尽管'a' == 'a'
。
def test(*values):
return values[0]=='a'
tuple = ('a',)
test(tuple)
Output: False
Output:
False
Using the *args syntax in the function declaration means that all parameters will be collected into a new tuple.在 function 声明中使用 *args 语法意味着所有参数都将被收集到一个新的元组中。 When you pass your tuple now to this function, it will create a tuple with only one element since you passed only one argument.
当你现在将你的元组传递给这个 function 时,它将创建一个只有一个元素的元组,因为你只传递了一个参数。 The value of
values
is (('a',),)
a tuple with tuple in it. values 的
values
是(('a',),)
一个包含元组的元组。 What you probably meant to do was to spread the tuple into the function call which involves the same asterisk syntax: test(*tuple)
which results in values == ('a',)
as you expected.您可能打算做的是将元组传播到 function 调用中,该调用涉及相同的星号语法:
test(*tuple)
会产生values == ('a',)
正如您所期望的那样。
It's because you are using *values
rather than values in your function definition这是因为您在 function 定义中使用
*values
而不是 values
When you use the special syntax *args
in a function, args
will already come back as a tuple, where each arg is an element of the tuple.当您在 function 中使用特殊语法
*args
时, args
将作为元组返回,其中每个 arg 都是元组的一个元素。
So for example所以例如
> def print_args(*args):
print(args)
> print_args('a', 'b', 'c')
# Outputs:
('a', 'b', 'c')
In your case since you are passing in a tuple already, w/in the functions values
is like "Ok, I'll happily take a tuple as my first argument", and values
becomes a tuple of tuples (well a tuple of a single tuple).在您的情况下,因为您已经传入了一个元组,所以函数中的
values
就像“好的,我很乐意将一个元组作为我的第一个参数”,并且values
变成一个元组的元组(以及一个单一的元组元组)。 Thus you are comparing ('a',) to 'a' and your check fails因此,您将 ('a',) 与 'a' 进行比较并且您的检查失败
TL;DR: either pass in just 'a'
or change *values
to values
TL;DR:要么只传入
'a'
,要么将*values
更改为values
def test(values):
return values[0] == 'a'
tuple = ('a',)
test(tuple)
# Outputs:
True
Modify your function like this:像这样修改您的 function :
def f(*v):
print(v)
return v[0] == 'a'
then call f(('a',)), you'll get (('a',),) False function gets a tuple ('a',) not 'a'然后调用 f(('a',)),你会得到 (('a',),) False function 得到一个元组 ('a',) 而不是 'a'
quote引用
def func(*args, **kwargs): ... var-keyword: specifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameters). def func(*args, **kwargs): ... var-keyword: 指定可以提供任意多个关键字 arguments(除了已经被其他参数接受的任何关键字 arguments 之外)。 Such a parameter can be defined by prepending the parameter name with **, for example kwargs in the example above.
可以通过在参数名称前加上 ** 来定义这样的参数,例如上面示例中的 kwargs。
https://docs.python.org/3/glossary.html#term-parameter https://docs.python.org/3/glossary.html#term-parameter
your not passing a pointer to the type using *args.您没有使用 *args 传递指向类型的指针。 the parser thinks your passing keyword arguments
解析器认为您传递的关键字 arguments
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.