簡體   English   中英

比較Python中非關鍵字args的可變數量

[英]Compare variable number of non-keyworded args in Python

我有一個函數,應該比較任意數量的給定輸入值,看看它們是否都具有相同的值

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個值,而第二個方法將在讀取第一對后立即退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM