gpt4 book ai didi

python - 从列表中的元组返回具有流量强度的日期

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:43 24 4
gpt4 key购买 nike

我试图在下面的函数中返回与流量强度匹配的所有日期,但我只将第一个元组的所有元素作为列表而不是所有匹配的元组。

def traffic_intensity(count):
"""Returns string indicating intensity level given by number of
vehicles"""
level_name = ""
if(count < 5000):
level_name = "Very Low"
elif(count >= 5000 and count < 10000):
level_name = "Low"
elif(count >= 10000 and count < 18000):
level_name = "Moderate"
elif(count >= 18000):
level_name = "High"
return(level_name)


def dates_with_intensity(vehicle_records, intensity):
"""Returns number of days with the given traffic intensity level"""
new_list = []
for number in vehicle_records:
date_count = number[0]
number_count = number[1]
traffic = traffic_intensity(number_count)
if traffic == intensity:
new_list += date_count
return new_list

对于测试数据

vehicle_records = [('2010-01-01',1),
('2010-01-02',2),
('2010-01-03',3)]
days = dates_with_intensity(vehicle_records, 'Very Low')
print(days)

我应该得到

['2010-01-01', '2010-01-02', '2010-01-03']

但我得到了

['2', '0', '1', '0', '-', '0', '1', '-', '0', '1']

有人可以帮我解决这个问题吗?

最佳答案

从 for 循环中获取返回值。 date_count 也不是数组,所以你应该使用 .append() 而不是加法:

def dates_with_intensity(vehicle_records, intensity):
"""Returns number of days with the given traffic intensity level"""
new_list = []
for number in vehicle_records:
date_count = number[0]
number_count = number[1]
traffic = traffic_intensity(number_count)
if traffic == intensity:
new_list.append(date_count)
return new_list

关于python - 从列表中的元组返回具有流量强度的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49869373/

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