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

荒凉一梦 提交于 2020-06-22 19:30:13

问题


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

mylist = [(a,1),(a,2),(b,3)]    
result = {}
for i in mylist:  
   result.setdefault(i[0],[]).append(i[1])
print(result)
>>> result = {a:[1,2], b:[3]}

I recall learning that most for loops can be re-written as comprehensions so I wanted to practice but I've failed for the past hour to make one work.

I read this: https://stackoverflow.com/a/56011919/2415706 and now I haven't been able to find another library that does this but I'm also not sure if this comprehension I want to write is a bad idea since append mutates things.


回答1:


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}


来源:https://stackoverflow.com/questions/62315048/list-of-tuples-to-dictionary-with-duplicates-keys-via-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!