我需要在從一個生成器讀取輸入的同時創建兩個字典。我很關心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?
你是什麼意思「這需要一個基礎迭代超過'第一'」?字典不需要迭代來分配新的項目,這是一個O(1)操作。 –
第二個版本更好,但假設它甚至可能,單個理解沒有任何好處。只需使用兩個字典理解。 –
複雜性是2O(n),它仍然是O(n)。如果您正在考慮速度和複雜性,兩者之間沒有顯着差異。 –