从一个单个迭代器中创建两个词典



我需要在一个发电机的输入时创建两个词典。我关心的是,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?

您的第二种方法可能是最好的方法,在dict中添加键不需要dict上的基本迭代。实际上,时间复杂性仅是o(1(,即恒定时间,并且独立于字典大小。

最新更新