2012-08-05 137 views
1

我希望我的函數根據調用參數返回多個字典。例如如果我調用沒有參數的函數,它應該返回所有的字典,如果我用參數列表調用它,它應該從函數返回相應的字典。顯然,如果我打電話沒有參數或一個參數,它工作正常,但我有多個值使用它的問題。以下示例顯示了此問題。根據調用參數從python函數返回多個字典

def mydef(arg1=None): 
    a = {'a1':1, 'a2':2} 
    b = {'b1':1, 'b2':2} 
    c = {'c1':1, 'c2':2} 
    d = {'d1':1, 'd2':2} 
    if arg1 is None: 
     return a,b,c,d 
    else: 
     for x in arg1: 
      if x == 'a': 
       return a 
      elif x == 'b': 
       return b 

w,x,y,z = mydef() 
print type(w) 
print w 

s,t = mydef(['a', 'b']) 
print type(s) 
print s 
print type(t) 
print t 

懷疑:列表返回,而不是類型的字典:

def mydef(args=None): 
    dicts = { 'a' :{'a1' : 1, 'a2' :2}, 'b' : {'b1' : 1, 'b2' :2}} 
    if args is None: 
     args = ['a', 'b'] 
    return [dicts[d] for d in args] 


x,y = mydef() 
type(x) 
>> type 'dict' 

type(y) 
>> type 'dict' 

x = mydef(['a']) 
type(x) 
>> type 'list' 

回答

11

函數只到達返回一次。您無法循環並嘗試在循環的每次迭代中返回一些內容;第一個返回並結束該功能。如果你想「返回多個值」,你真正必須做的是返回一個包含它們的值,比如值的列表或者元組的值。

此外,最好將字典放在字典中(sup dawg),而不是使用局部變量來命名它們。然後你可以用鑰匙把它們挑出來。

這裏做的是返回所選類型的字典列表的方式:

>>> def returnDicts(args=None): 
...  dicts = { 
...   'a': {'a1':1, 'a2':2}, 
...   'b': {'b1':1, 'b2':2}, 
...   'c': {'c1':1, 'c2':2}, 
...   'd': {'d1':1, 'd2':2} 
...  } 
...  if args is None: 
...   args = ['a', 'b', 'c', 'd'] 
...  return [dicts[d] for d in args] 
>>> returnDicts() 
[{'a1': 1, 'a2': 2}, 
{'b1': 1, 'b2': 2}, 
{'c1': 1, 'c2': 2}, 
{'d1': 1, 'd2': 2}] 
>>> returnDicts(['a']) 
[{'a1': 1, 'a2': 2}] 
>>> returnDicts(['a', 'b']) 
[{'a1': 1, 'a2': 2}, {'b1': 1, 'b2': 2}] 
+2

+1「sup dawg」。 – Blender 2012-08-05 07:30:25

+0

Minor nitpick:我會寫'args = dicts.keys()',這樣你的函數就可以按原樣工作,如果你添加更多字典 – 2012-08-05 07:35:47

+0

lol @ dog評論。 – klobucar 2012-08-05 07:44:40

0

爲什麼不把它們類型的字典的類型的字典,像這樣

def mydicts(arg1=None): 
    dicter = {'a': {'a1':1, 'a2':2}, 
       'b': {'b1':1, 'b2':2}, 
       'c': {'c1':1, 'c2':2}, 
       'd': {'d1':1, 'd2':2}, 
       } 

    #if arg1 is None return all the dictionaries. 
    if arg1 is None: 
     arg1 = ['a', 'b', 'c', 'd'] 

    # Check if arg1 is a list and if not make it one 
    # Example you pass it a str or int 

    if not isinstance(arg1, list): 
     arg1 = [arg1] 

    return [dicter.get(x, {}) for x in arg1] 

注意,這也將返回一個列表的項目回給你。

+0

我試過你的解決方案,在這裏當我傳遞參數,然後返回的值是列表而不是字典。此外,返回的列表中也只包含密鑰,因此顯式轉換也不會幫助 – sarbjit 2012-08-18 15:24:52

+0

我修復了一個語法錯誤,並且如果您閱讀它,說「注意,這也會返回一個項目列表給您。」當我運行這個程序時,我看到完整的字符串,而不僅僅是鍵。 {[b1':1,'b2':2}, {'c1':1,'a2':2} ':1,'c2':2}, {'d1':1,'d2':2} ] – klobucar 2012-08-23 05:57:10

+0

我試着用你編輯過的代碼,當arg通過時仍然返回列表。請在原始問題中查看我的編輯,以顯示我如何使用它。我用你的,因爲它只是用我的編輯描述。 – sarbjit 2012-08-23 15:09:33

相關問題