将字典键(DateTime)与元组列表进行比较[1],如果匹配返回元组[0]
我是 Python 的初学者,在获取正确的语法方面遇到了困难。非常感谢任何帮助!
我有一本字典和一个元组列表。我想将字典的键与元组中的值进行比较,如果满足条件,则返回不同的元组值。示例如下:
dictionary = {datetime.datetime(2022, 4, 12, 9, 30): 30, datetime.datetime(2022, 4, 12, 11, 0): 60, datetime.datetime(2022, 4, 12, 13, 0): 30}
tuplelist = [(1, datetime.time(6, 45, 21)), (2, datetime.time(7, 15, 21)), (3, datetime.time(7, 45, 21)...etc)
目标是查看我的字典键属于哪个 30 分钟增量,并使用元组列表中存储的增量编号更新它。我尝试过的:
for k,y in dictionary:
for i, t in tuplelist:
if t <= k <= (t+ datetime.timedelta(minutes = 30)):
dictionary[k] = t
我得到的错误是无法解压不可迭代类型日期时间。
欢迎任何帮助和/或解释!我真的很喜欢学习编码,但不是来自计算机科学背景,所以除了正确的语法之外,我总是在寻找它的工作原理。
谢谢你!
工作解决方案更新:
newdic = {}
for k,v in dictionary.items():
for item in mylist:
i, t = item
if t <= k.time() <= (datetime.combine(datetime.today(),t) + datetime.timedelta(minutes=30)).time():
newdic.update({i : v})
else:
continue
I am a beginner(ish) with Python and having trouble with getting the correct syntax for this. Any help is greatly appreciated!
I have a dictionary and a list of tuples. I would like to compare the key of my dictionary to a value in the tuple, and if meets criteria return a different tuple value. Here's the illustration:
dictionary = {datetime.datetime(2022, 4, 12, 9, 30): 30, datetime.datetime(2022, 4, 12, 11, 0): 60, datetime.datetime(2022, 4, 12, 13, 0): 30}
tuplelist = [(1, datetime.time(6, 45, 21)), (2, datetime.time(7, 15, 21)), (3, datetime.time(7, 45, 21)...etc)
The goal is to see which increment of 30 minutes my dictionary key falls into, and update it with the increment number stored in tuple list. What I tried:
for k,y in dictionary:
for i, t in tuplelist:
if t <= k <= (t+ datetime.timedelta(minutes = 30)):
dictionary[k] = t
The error I got is unable to unpack non iterable type datetime.
Any help and/or explanation is welcome! I am really enjoying learning to code but not from a CS background so always looking for the how it works in addition to just the correct syntax.
Thank you!
Update for working solution:
newdic = {}
for k,v in dictionary.items():
for item in mylist:
i, t = item
if t <= k.time() <= (datetime.combine(datetime.today(),t) + datetime.timedelta(minutes=30)).time():
newdic.update({i : v})
else:
continue
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是完整的答案。查看是否有助于解决早期问题。
This is not the complete answer. See if it helps resolve early issues up to the comment.