簡體   English   中英

從字典和列表解壓縮參數

[英]Unpacking arguments from dict and list

我有一本字典:

x = {'#33a02c': 1.8, '#5eb22d': 0.0, '#89c42e': 1.2}

和清單:

y = ['#33a02c', '#5eb22d', '#89c42e']

我可以得到:

test = x[y[0]] 

獲取字典的值。 如何使用*args創建一個可以解壓縮表達式的函數? 我努力了:

def my_function(*args):
   test= x[y[args]]
   return test

這顯然不能按預期工作

如果您希望使用傳遞給函數的索引來獲取元素列表,則可以使用列表推導-

def my_function(*args):
   if len(args) == 0:
       return x[y[args[0]]]
   return [x[y[a]] for a in args]

operator.itemgetter() operator模塊中的內置operator.itemgetter() 參見https://docs.python.org/2/library/operator.html#operator.itemgetter

如果您想自己做:

def my_function(*args):
   def extract_keys(dict_var):
      return [dict_var[key] for key in args]
   return extract_keys

用於:

x = {'#33a02c': 1.8, '#5eb22d': 0.0, '#89c42e': 1.2}
y = ['#33a02c', '#5eb22d', '#89c42e']

print operator.itemgetter(*y)(x)
print my_function(*y)(x)

我不會在這里使用* args。 嘗試這個:

def myfunction(z):
    return [x[c] for c in z]

然后您可以遍歷返回的列表,如下所示:

for q in myfunction(['#33a02c', '#5eb22d', '#89c42e']):
    print q

暫無
暫無

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

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