Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
比较Python中非关键字参数的可变数量_Python_Variables_Compare_Args - Fatal编程技术网

比较Python中非关键字参数的可变数量

比较Python中非关键字参数的可变数量,python,variables,compare,args,Python,Variables,Compare,Args,我有一个函数,可以比较任意数量的给定输入值,看看它们是否都有相同的值 def compare(self, message, *args): pars = list(args) #since args is stored in a tuple len = len(pars) I am not sure how to proceed with the comparison - earlier I was using 2 variables "val1 and val2" wh

我有一个函数,可以比较任意数量的给定输入值,看看它们是否都有相同的值

def compare(self, message, *args):
    pars = list(args) #since args is stored in a tuple
    len = len(pars) 



I am not sure how to proceed with the comparison - earlier I was using 2 variables "val1 and val2" which was assuming that I am comparing only 2 variables but i want to make it possible to compare more than 2 parameters.
我有个想法

     d = 0  #index
     for i in pars: 
         x_d = i
         d = d+1
所以x_d是x_0,x_1,x_2。将有和参数长度一样多的索引,然后我可以把x_d(所有的)放在一个列表中,只说len(set(the_list))==1。。差不多吧。不确定是否有更好的方法

有什么建议吗

====================== 我在这里提出了一个解决方案-不确定这对字典会起什么作用(可能有人会建议我如何在下面的函数中处理它??),但在这里我将*args(一个元组)转换为一个列表

>>> def compare(list):
...     if len(params) > 1:
...         if len(set(list)) == 1:
...             print "MATCH"
...         else:
...             print "NOT MATCHING"
... 
>>> params1 = [ 4, 4, 4]
>>> compare(params1)
MATCH
>>> params = [ 3, 4, 5]
>>> compare(params)
NOT MATCHING

如果您要传递的所有项都是可散列的(因此可以放入一个集合),那么您可以使用一个集合来完成,就像您所想的那样,如下所示

def compare(self, message, *args):
    if len(set(args)) > 1:
        # not all args are the same
    else:
        # args are all the same
但是,有些东西(如列表或字典)是不可散列的,但仍然可以进行比较。在这种情况下,您需要进行实际比较:

def compare(self, message, *args):
    for item in args[1:]:
        if args[0] != item:
            # not all args are the same
            break
    else:
        # all args are the same
请注意,为了简洁起见,我在比较中使用了
args[0]
;通过将
args[0]
的值存储在变量中,可以节省一些查找,但是还需要检查以确保
args
的长度非零


还要注意,后一种方法实际上比
set
方法更有效。为什么?因为它会短路-如果
args
中有1000个元素,但前两个元素不相等,那么第一个方法仍将读取所有1000个值,而第二个方法将在读取第一对后立即退出。

不确定它是如何工作的,因为args是元组格式。。你能给我一个更具体的例子吗?元组的行为和列表完全一样,只是你不能修改它们。您仍然可以对它们进行切片,这就是上面的
args[1://code>所做的,并对它们进行索引,这就是
args[0]
所做的。还有一件事。。if/else在一起,对吗,Amber?这些语句都在一起,是的。谢谢Amber-跟着它。