从dict和list中解压缩参数

时间:2015-10-13 09:49:25

标签: python dictionary

我有一本字典:

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

显然没有按预期工作

3 个答案:

答案 0 :(得分:1)

如果您期望使用传入函数的索引的元素列表,您可以使用列表理解 -

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

答案 1 :(得分:0)

operator.itemgetter()模块中的内置operator。见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)

答案 2 :(得分:0)

我不会在这里使用* args。试试这个:

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

然后你可以迭代它返回的列表,如下所示:

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