我有两本字典:
timing = [
{"day_name": "sunday"},
{"day_name": "monday"},
{"day_name": "tuesday"},
{"day_name": "wednesday"},
{"day_name": "thursday"},
{"day_name": "friday"},
{"day_name": "saturday"},
]
hours_detail = [
{"day_name": "sunday", "peak_hour": False},
{"day_name": "monday", "peak_hour": False},
{"day_name": "tuesday", "peak_hour": False},
{"day_name": "wednesday", "peak_hour": False},
{"day_name": "thursday", "peak_hour": False},
{"day_name": "friday", "peak_hour": False},
{"day_name": "saturday", "peak_hour": False},
{"day_name": "saturday", "peak_hour": True},
{"day_name": "friday", "peak_hour": True},
{"day_name": "thursday", "peak_hour": True},
]
我想创建另一个字典列表,看起来像下面的一个。我基本上是结合这两个列表,并根据日期名称重新排列。
final_data_object = [
{
"timing": {"day_name": "saturday"},
"hour_detail": [
{"day_name": "saturday", "peak_hour": False},
{"day_name": "saturday", "peak_hour": True},
]
},
{
"timing": {"day_name": "friday"},
"hour_detail": [
{"day_name": "friday", "peak_hour": False},
{"day_name": "friday", "peak_hour": True},
]
},
soon on...
]
我试过这个,但没有用:
data = []
for time_instance in timing:
obj = {
"timing": time_instance
}
for hour_instance in hour_detail:
if time_instance["day_name"] == hour_instance["day_name"]:
obj["hour_detail"] = hour_instance
data.append(obj)
return data
2条答案
按热度按时间jc3wubiy1#
如果
pricing = hour_detail
,则obj["pricing"]
必须是列表,因为它可以有多个值。你必须在循环
for time_instance in timing:
中创建一个新的列表,并在每次time_instance["day_name"] == pricing_instance["day_name"]
时追加。示例:
或更小的方式
O(n*m)的时间复杂度,首先通过哈希表{day_name:时间复杂度为O(n + m),所以时间复杂度为O(n+m)
xxhby3vn2#
这应该可以回答您的问题: