gpt4 book ai didi

python - 给定键适合一定的间隔,如何在 python 中打印出字典的值?

转载 作者:行者123 更新时间:2023-12-01 05:06:25 25 4
gpt4 key购买 nike

我试图根据字符串值的键是否在特定日期的间隔内来打印字符串值。例如:

fileDict = {"2006-01-01":"A", "2006-01-02":"B", "2006-01-03":"C", "2006-01-04":"D", "2006-01-05":"E"}

startTime = "2006-01-01" #January 1, 2006
endTime = "2006-01-05" #January 5, 2006

if fileDict.keys >= startTime and fileDict.keys <= endTime:
print fileDict.values()

因此在这种情况下,每个值都应该打印出来。

最佳答案

使用 datetime.strptime 进行转换然后比较:

 import datetime
fileDict = {"2006-01-01":"A", "2006-01-02":"B", "2006-01-03":"C", "2006-01-04":"D", "2006-01-05":"E","2006-01-06":"F"}

startTime = datetime.datetime.strptime("2006-01-01","%Y-%m-%d")
endTime = datetime.datetime.strptime("2006-01-05","%Y-%m-%d")

for k in fileDict:
dat = datetime.datetime.strptime(k,"%Y-%m-%d")
if startTime <= dat <= endTime:
print fileDict[k]
C
B
A
E
D

我使用<=基于您想要将上限和下限包含在范围内的假设

关于python - 给定键适合一定的间隔,如何在 python 中打印出字典的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918960/

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