从一个迭代器

时间:2017-05-04 09:12:36

标签: python performance dictionary iterator

我需要在从一个生成器读取输入时创建两个词典。我担心的是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?

1 个答案:

答案 0 :(得分:3)

您的第二种方法可能是最好的方法,为dict添加密钥不需要对dict进行基础迭代。事实上,时间复杂度只是O(1),即恒定时间,与字典大小无关。