[英]Python: mimic the effect of groupby with list/dict comprehension
我需要轉換字典列表:
original = [
{'type': 'a', 'length': 34, 'width': 74},
{'type': 'a', 'length': 15, 'width': 22},
{'type': 'b', 'length': 53, 'width': 54},
{'type': 'b', 'length': 11, 'width': 45},
]
轉換為以key type
為鍵的值的字典:
expected = {
'a': [
{'type': 'a', 'length': 34, 'width': 74},
{'type': 'a', 'length': 15, 'width': 22},
],
'b': [
{'type': 'b', 'length': 53, 'width': 54},
{'type': 'b', 'length': 11, 'width': 45},
],
}
這可以通過itertools.groupby
或通過手動遍歷列表來實現,但是itertools.groupby
列表/字典理解有什么方法嗎?
您可以執行以下操作:
{t: [i for i in original if i['type'] == t] for t in {i['type'] for i in original}}
但它既難以閱讀,又具有最壞的運行時復雜度O(n²) ,其中n是列表中的項目數。 在排序列表上使用itertools.groupby
既快捷又容易閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.