简体   繁体   English

Python:生成器中的产量字典元素?

[英]Python: Yield Dict Elements in generators?

Before I say a word, let me thank the community for being the authoritative location for my programming queries as of recent.在我说一句话之前,让我感谢社区成为我最近的编程查询权威位置。 And pretend those compliments weren't expressed using words.并假装这些赞美不是用语言表达的。 Anyway, the law of probability dictated that I stumble across something I couldn't find using the versatile search bar, so I've decided to explicitly ask for the first time.无论如何,概率法则决定了我偶然发现了使用多功能搜索栏找不到的东西,所以我决定第一次明确要求。 Maybe I just wasn't searching using Pythonic-enough lingo.也许我只是没有使用足够 Pythonic 的术语进行搜索。 Or perhaps I suck at Googling/Stackoverflowing.或者我可能不喜欢谷歌搜索/Stackoverflowing。 Regardless...不管...

I'm toying with Python coroutines and generators.我正在玩弄 Python 协程和生成器。 From what I can gather, you can do anything a generator-comprehension can with producer coroutines, albeit more verbosely.据我所知,你可以用生产者协程做任何生成器理解可以做的事情,尽管更冗长。 I'm currently using Python 3, although any answers regarding Python 2 as well wouldn't go a miss.我目前正在使用 Python 3,尽管关于 Python 2 的任何答案也不会 go 错过。

So I'm assuming the following code fragments are equivalent:所以我假设以下代码片段是等价的:

one_to_three = (num for num in range(1, 4))

... ...

def one_to_three():
    for num in range(1, 4):
        yield num

one_to_three_gen = one_to_three()

It works on my Python installation.它适用于我的 Python 安装。 If I ignore the redundancy-so-common-in-examples featured in that code, I see that the generator comprehension maps easily to the generator made by the producer coroutine.如果我忽略该代码中的冗余示例,我会发现生成器理解很容易映射到生产者协程生成的生成器。 Being Dr. Pragmatic, I tried mapping the same concept to dicts, given that dict comprehensions already exist, with me thinking these two would be equivalent:作为 Pragmatic 博士,我尝试将相同的概念映射到 dicts,因为 dict 理解已经存在,我认为这两个是等价的:

one_to_three_doubles = {num : num * 2 for num in range(1, 4)}

... ...

def one_to_three_doubles():
    for num in range(1, 4):
        yield num : num * 2

one_to_three_doubles_gen = one_to_three_doubles()

The first one works, but the second does not.第一个有效,但第二个无效。 It flags a syntax error on the colon on the 3rd line.它在第 3 行的冒号上标记语法错误。

Now, either I'm slipping up very slightly on the syntax, or I have a massive misunderstanding of how producer coroutines work.现在,要么我在语法上稍有失误,要么我对生产者协程的工作方式有很大的误解。 I suspect it's failing for the same reason you can't make a coroutine return a list as opposed to a generator, but I don't really know.我怀疑它失败的原因与你不能让协程返回列表而不是生成器的原因相同,但我真的不知道。

So yeah, a fix to that error is basically what I'm asking for;所以,是的,修复该错误基本上就是我所要求的; thanks in advance.提前致谢。 I'd prefer a answer that tells me the answer as opposed to giving me a whole new way of achieving the result, but obviously if it's the only way...我更喜欢一个能告诉我答案的答案,而不是给我一种全新的方式来实现结果,但显然如果这是唯一的方式......

Dict comprehensions do work like list/set comprehensions and generator expressions - an X comprehension with a "body" of expr for vars in iterable is pretty much equivalent to X(expr for vars in iterable) - and you already know how to turn a generator expression into a generator.字典推导确实像列表/集合推导和生成器表达式一样工作 - 带有expr for vars in iterable的 X 推导几乎等同于X(expr for vars in iterable) - 你已经知道如何打开生成器表达式到生成器中。 But note the "pretty much" bit, as a literal translation doesn't work (as you noticed) and isn't necessary at all (doesn't make the implementation much easier and would actually be quite hacky).但请注意“相当多”位,因为直译不起作用(正如您所注意到的)并且根本没有必要(不会使实施变得更容易,实际上会很hacky)。

Dict comprehension just have a tiny bit of syntactic sugar to look more like dict literals (the colon).字典理解只是有一点语法糖看起来更像字典文字(冒号)。 Semantically, it's not necessary - there is nothing special about it.从语义上讲,它没有必要——它没有什么特别之处。 Stop and think about it for a second: The dict comprehension must produce two values on each iteration, a key and a value.停下来想一想:dict 理解必须在每次迭代中产生两个值,一个键和一个值。 That's exactly what the colon stands for - (key, value) pairs (remember that dict accepts an iterable of (key, value) pairs).这正是冒号所代表的 - (key, value)对(请记住dict接受可迭代的(key, value)对)。 You can't use that syntactic sugar outside of dict comprehensions, but you can just use tuples for the pairs.您不能在 dict 理解之外使用该语法糖,但您可以只对对使用元组。 Therefore, the equivalent generator would be:因此,等效的生成器将是:

def one_to_three_doubles():
    for num in range(1, 4):
        yield num, num * 2

I wanted to generate a dict from yield in a python function and found this question.我想从 python function 中的产量生成一个字典并找到了这个问题。 Below is code for returning a dict.下面是返回字典的代码。

def _f():
    yield 'key1', 10
    yield 'key2', 20

def f(): return dict(_f())

print(f())
# Output:
{'key1': 10, 'key2': 20}

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

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