如何解决在字典中过滤日期 - python
我有一本这样的字典:
> { "Country1": {"time": [1/22/20,1/23/20...],"cases":[0,10,20,...]},> "Country2": {"time": [1/22/20,> .... }
我想删除高于给定日期的日期及其各自的情况。我试过这个,但它失败了,因为 IndexError: list index out of range。你会怎么做?
for i in (range(len(Country_Region))):
for j in (range(len(Countries_Dict[i][Country_Region[i]]['time']))):
if datetime.strptime(Countries_Dict[i][Country_Region[i]]['time'][j],'%m/%d/%y') > datetime.strptime(date,'%m-%d-%y'):
Countries_Dict[i][Country_Region[i]]['time'].pop(j)
Countries_Dict[i][Country_Region[i]]['cases'].pop(j)
日期是字符串格式,所需的输出是和以前一样的字典,没有高于给定日期的日期及其各自的情况。
解决方法
您的 IndexError
可能是数据不一致造成的,time
和 cases
的长度不同。
您可以使用 zip
将它们聚集在一起,以较小列表的长度剪裁。
data = {
'Country1': {
'time': ['1/22/20','1/23/20','1/24/20','1/25/20'],'cases': [0,10,20,30,40] # Inconsistent data
},'Country2': {
'time': ['1/22/20',30]
}
}
threshold_date = '1/23/20'
def parse_date(date):
return datetime.strptime(date,'%m/%d/%y')
for country,country_data in data.items():
pre_threshold = [
(time,case)
for time,case in zip(country_data['time'],country_data['cases'])
if parse_date(time) <= parse_date(threshold_date)
]
country_data['time'] = [t for t,c in pre_threshold]
country_data['cases'] = [c for t,c in pre_threshold]
这将导致,
{'Country1': {'time': ['1/22/20','1/23/20'],10]},'Country2': {'time': ['1/22/20',10]}}
请注意,第一个列表在 time
和 cases
中有 4 对 5 个条目,但这并不重要。
这是创建一个新列表,可以提高此代码的效率,但为了可读性,我保留了它。您可以根据需要选择这样做。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。