gpt4 book ai didi

python - 在 Python 中按复合键分组

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:06 24 4
gpt4 key购买 nike

我有一个这样的 CSV 文件:

route|id|alias|longitude|latitude
A|1|first|-33.51808226|-70.58256582
A|1|first|-33.52850414|-70.57645648
B|2|second|-33.51952529|-70.58043875
B|2|second|-33.53452223|-70.58343824

每条路线都有一个 id 和一个 alias,它们对于相同的 route 总是相同的。此外,每个 route 都有一组 points,每个点都由 longitudelatitude 组成。我正在尝试按 routepoints 进行分组,但我想生成文件的每个字段。

当我使用 itertools groupbyroute 分组时,我只能生成 routepoints:

with open(self.datafile, "r") as f:
reader = csv.DictReader(f, delimiter='|')
# Group data using 'route' as key
for route, points in groupby(reader, lambda p: p['route']):
points = list(points)
points = [
{
'longitude': p['longitude'],
'latitude': p['latitude']
} for p in points
]
yield {
"_source": {
"route": route,
"points": points
}
}

我尝试了不同的方法来获取该 routeidalias(比如使用 route['id']p['id'] 来获取 id 或在现有的之外使用另一个),但它们都不起作用。

有没有办法在使用 groupby 时使用组合键?或者可能是我的问题更简单的解决方案?

我希望能够产生这个:

yield {
"_source": {
"route": route,
"id": id,
"alias": alias,
"points": points
}
}

最佳答案

您确实可以使用复合键groupby:

# Group data using 'route', 'id', 'alias' as key
for route_id_alias, values in itertools.groupby(reader, lambda p: (p['route'], p['id'], p['alias'])):
points = [
{
'longitude': p['longitude'],
'latitude': p['latitude'],
} for p in values
]
print( {
"_source": {
"route": route_id_alias[0],
"id": route_id_alias[1],
"alias": route_id_alias[2],
"points": points,
}
})

当您产生结果时,您只需要通过索引访问您的 key 。

Try it online!

关于python - 在 Python 中按复合键分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com