我有一本这样的字典:
> { "Country1": {"time": [1/22/20, 1/23/20...], "cases":[0,10,20,...]},
> "Country2": {"time": [1/22/20, 1/23/20...], "cases":[0,10,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', '1/23/20', '1/24/20', '1/25/20'],
'cases': [0, 10, 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'], 'cases': [0, 10]},
'Country2': {'time': ['1/22/20', '1/23/20'], 'cases': [0, 10]}}
请注意,第一个列表在 time
中有 4 对 5 条目。和 cases
但没关系。这是创建一个新列表,可以提高此代码的效率,但为了可读性,我保留了它。您可以根据需要选择这样做。
关于python - 在字典中过滤日期 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67130718/