如果可能的話,一直在考慮如何將其轉換為單列:
activities =
[ {'type': 'Run', 'distance': 12345, 'other_stuff': other ...},
{'type': 'Ride', 'distance': 12345, 'other_stuff': other ...},
{'type': 'Swim', 'distance': 12345, 'other_stuff': other ...} ]
目前正在使用:
grouped_distance = defaultdict(int)
for activity in activities:
act_type = activity['type']
grouped_distance[act_type] = activity['distance']
# {'Run': 12345, 'Ride': 12345, 'Swim': 12345}
試過
grouped_distance = {activity['type']:[sum(activity['distance']) for activity in activities]}
這在它說活動['type']沒有定義的地方不起作用。
更新: 對發布的所有解決方案進行了一些基準測驗。1000 萬件商品,有 10 種不同的型別:
方法1(計數器):7.43s
方法2(itertools @chepner):8.64s
方法3(組@Dmig):19.34s
方法4(pandas @db):32.73s
方法5(Dict @db):10.95s
在 Raspberry Pi 4 上進行了測驗,以進一步了解差異。如果我錯誤地“命名”了該方法,請糾正我。
謝謝大家,@Dmig、@Mark、@juanpa.arrivillaga 激起了我對表演的興趣。更短/更整潔≠更高的性能。只想問我是否以單行形式寫它以使其看起來更整潔,但我學到的遠不止這些。
uj5u.com熱心網友回復:
您的解決方案雖然很好,但如果您真的想要單線:
act = [{'type': 'run', 'distance': 4}, {'type': 'run', 'distance': 3}, {'type': 'swim', 'distance': 5}]
groups = {
t: sum(i['distance'] for i in act if i['type'] == t)
for t in {i['type'] for i in act} # set with all possible activities
}
print(groups) # {'run': 7, 'swim': 5}
UPD:我進行了一些性能研究,將這個答案與使用group(sortedby(...)). group(sortedby(...))事實證明,在 1000 萬個條目和 10 種不同型別上,這種方法以18.14秒為單位輸給了10.12. 因此,雖然它更具可讀性,但它在更大的串列上效率較低,尤其是在其中具有更多不同型別的情況下(因為它對每個不同型別的初始串列迭代一次)。
但請注意,從問題開始的直接方法只需5幾秒鐘!
此答案僅出于教育目的顯示單行,問題的解決方案具有更好的性能。你不應該使用這個而不是一個有問題的,除非,正如我所說,你真的想要/需要單線。
uj5u.com熱心網友回復:
使用itertools.groupby.
from operator import itemgetter
by_type = itemgetter('type')
distance = itemgetter('distance')
result = {
k: sum(map(distance, v))
for k, v in groupby(sorted(activities, key=by_type), by_type)
}
當迭代groupby實體時,k將是活動型別之一,并且v將是具有型別的活動的可迭代k。
uj5u.com熱心網友回復:
d = {}
for x in activities: d.__setitem__(x["type"], d.get(x["type"], 0) x["distance"])
d
# {'Run': 12345, 'Ride': 12345, 'Swim': 12345}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/481935.html
