【问题标题】:Python - Loop through lists and join them when they matchPython - 遍历列表并在匹配时加入它们
【发布时间】:2022-11-20 07:28:03
【问题描述】:

我有一个列表字典。我必须尽可能循环加入他们。加入他们时,我必须将两列加在一起。我可以使用字典或列表。取决于什么是最简单的/推荐的。

例如

id name date value
1 hotel1 22-11-22 90
2 hotel2 22-11-22 90
3 hotel3 22-11-22 90
4 hotel1 23-11-22 10
5 hotel2 23-11-22 60
6 hotel3 23-11-22 90

所以我想遍历字典并提供以下结果:

{
    "hotelName": "hotel1",
    "date": "22-11-22",
    "value": "100"
}
{
    "hotelName": "hotel2",
    "date": "22-11-22",
    "value": "150"
}
{
    "hotelName": "hotel3",
    "date": "22-11-22",
    "value": "180"
}

欢迎任何指导提示

我尝试遍历列表,但我只能输出

{
    "hotelName": "hotel1",
    "date": "22-11-22",
    "value": "90"
}
{
    "hotelName": "hotel2",
    "date": "22-11-22",
    "value": "90"
}
{
    "hotelName": "hotel3",
    "date": "22-11-22",
    "value": "90"
}
{
    "hotelName": "hotel1",
    "date": "23-11-22",
    "value": "10"
}
{
    "hotelName": "hotel2",
    "date": "23-11-22",
    "value": "60"
}
{
    "hotelName": "hotel3",
    "date": "23-11-22",
    "value": "90"
}

【问题讨论】:

  • 请重写你的问题,目前没有意义
  • 还请发布列表字典。

标签: python list dictionary


【解决方案1】:

这是一个尝试 =)

hotels = {}
for ind,row in df.iterrows():
    hotel = row['name']
    if hotel in hotels:
        hotels[hotel]['value'] += row['value']
        hotels[hotel]['date'].append(row['date'])
    else:
        hotels[hotel] = {
            'value': row['value'],
            'date': [row['date']]
        }
print(hotels)

输出:

{'hotel1': {'value': 100, 'date': ['22.11.2022', '23.11.2022']},
 'hotel2': {'value': 150, 'date': ['22.11.2022', '23.11.2022']},
 'hotel3': {'value': 180, 'date': ['22.11.2022', '23.11.2022']}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2021-06-14
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多