简体   繁体   English

解包函数将元组返回到键值对

[英]Unpack function return tuple into key value pair

Suppose I have a function that returns a tuple: 假设我有一个返回元组的函数:

def foo(x):
  return (x, x*100)

I have a list of values that I'd like to apply the function on and then turn the results into a dictionary: 我有一个值列表,我想要应用该函数,然后将结果转换为字典:

list_of_vals = [2, 4, 6]
result = {...magic comprehension...}
print(result)
# {2: 200, 4: 400, 6: 600}

I've come up with two ways to do this: 我想出了两种方法:

{ k: v for k, v in map(foo, list_of_vals)}
{ k: v for k, v in (foo(val) for val in list_of_vals} # equivalently

or: 要么:

def helper_bar(vals):
  for val in vals:
    yield(foo(val))

{k: v for k, v in helper_bar(vals)}

However, none of these is very readable. 但是,这些都不是非常易读。 Furthermore, if the list_of_vals is humongous I don't want to create extra copies. 此外,如果list_of_vals非常庞大,我不想创建额外的副本。 Is there any better (efficient?) way to do this assuming I have very long list of values and foo is an expensive function? 假设我有很长的值列表并且foo是一个昂贵的函数,有没有更好的(有效的?)方法来做到这一点?

You can also use the dict initializator that takes an iterable of key-value tuples . 您还可以使用带有可迭代键值元组dict初始化器 So this would be perfect for your function that already returns a tuple: 所以这对于已经返回元组的函数来说是完美的:

>>> dict(map(foo, list_of_vals))
{2: 200, 4: 400, 6: 600}

In general though, having a function that returns a key-value tuple with the identical key seems somewhat rare. 通常,具有返回具有相同键的键值元组的函数似乎有点罕见。 Most commonly, you would just have a function that returns the value. 最常见的是,您只需要一个返回值的函数。 In those cases you would use a dictionary comprehension like this: 在这些情况下,您将使用这样的字典理解:

{ x: foo(x) for x in list_of_vals }

Just convert the result of map to dict directly 只需将map的结果直接转换为dict即可

>>> list_of_vals = [2, 4, 6]
>>> dict(map(foo, list_of_vals))
{2: 200, 4: 400, 6: 600}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM