从一个i创建两个词典

2024-03-28 12:06:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建两个字典,同时阅读输入从一个发电机。我关心的是dict和数据原则上只需要滚动一次。我该怎么办?你知道吗

# dummy data
def data():
    yield 'a', 5
    yield 'b', 8
    yield 'c', 12

# two iterations, bad.
first  = {k: v + 1 for k, v in data()}
second = {k: 2 * v for k, v in data()}

# One iteration only, but it scans both dicts on each step?
first  = {}
second = {}
for k, v in data():
    first[k]  = v # this needs an underlying iteration over `first`, right?
    second[k] = v # and this needs another underlying iteration over `second`..

# Is there aa.. multiple comprehension?
first, second = {k: v + 1, k: 2 * v for k, v in data()} # SyntaxError
# Would it be just equivalent to the previous loop?

Tags: infordata字典itthis发电机over