<p>一种基于使用<a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">^{<cd1>}</a>对值进行分组的方法是执行以下操作:</p>
<pre><code>from collections import defaultdict
from operator import itemgetter
import pprint
list_pts = [
{'city': 'Madrid', 'year': '2017', 'date': '05/07/2017', 'pts': 7},
{'city': 'Madrid', 'year': '2017', 'date': '14/11/2017', 'pts': 5},
{'city': 'Londres', 'year': '2018', 'date': '25/02/2018', 'pts': 5},
{'city': 'Paris', 'year': '2019', 'date': '17/04/2019', 'pts': 4},
{'city': 'Londres', 'year': '2019', 'date': '15/06/2019', 'pts': 8},
{'city': 'Paris', 'year': '2019', 'date': '21/08/2019', 'pts': 8},
{'city': 'Londres', 'year': '2019', 'date': '04/12/2019', 'pts': 2}]
# function for extracting city and year (to be used as a grouping key)
city_and_year = itemgetter("city", "year")
# function for extracting dates and points
date_and_points = itemgetter("date", "pts")
# group by key (city, year) by using a defaultdict
res = defaultdict(list)
for record in list_pts:
res[city_and_year(record)].append(date_and_points(record))
# transform to the desired format
result = []
for (city, year), values in res.items():
dates, points = zip(*values)
result.append({"city": city, "year": year, "dates": list(dates), "pts": list(points)})
# use pprint to nicely print the output
pprint.pprint(result)
</code></pre>
<p><strong>输出</strong></p>
<pre><code>[{'city': 'Madrid',
'dates': ['05/07/2017', '14/11/2017'],
'pts': [7, 5],
'year': '2017'},
{'city': 'Londres', 'dates': ['25/02/2018'], 'pts': [5], 'year': '2018'},
{'city': 'Paris',
'dates': ['17/04/2019', '21/08/2019'],
'pts': [4, 8],
'year': '2019'},
{'city': 'Londres',
'dates': ['15/06/2019', '04/12/2019'],
'pts': [8, 2],
'year': '2019'}]
</code></pre>