List of tuples to dictionary with duplicates keys via list comprehension?

前端 未结 1 1594
再見小時候
再見小時候 2021-01-13 09:45

I have a list of tuples with duplicates and I\'ve converted them to a dictionary using this code I found here:

https://stackoverflow.com/a/61201134/2415706



        
1条回答
  •  攒了一身酷
    2021-01-13 10:03

    Comprehension is meant to map items in a sequence independent of each other, and is not suitable for aggregations such as the case in your question, where the sub-list an item appends to depends on a sub-list that a previous item appends to.

    You can produce the desired output with a nested comprehension if you must, but it would turn what would've been solved in O(n) time complexity with a loop into one that takes O(n ^ 2) instead:

    {k: [v for s, v in mylist if s == k] for k, _ in mylist}
    

    0 讨论(0)
提交回复
热议问题