从MySQL查询中我得到的数据是我放入字典“d”:
d = {0:(datetime.timedelta(0, 25200),),1:(datetime.timedelta(0, 25500),),2:(datetime.timedelta(0, 25800),),3:(datetime.timedelta(0, 26100),),4:(datetime.timedelta(0, 26400),),5:(datetime.timedelta(0, 26700),)}
我有一个列表“m”,其数字如下:
m = [3,4,1,4,7,4]
我想测试“m”,如果有数字“4”,我想收到另一个列表“h”,其中小时为“d”,其中列表“m”的索引与键对应从字典“d”开始,所以:m [1],m [3],m [5]会把我的时间分配到列表“h”中的d [1],d [3],d [5]:
h = [7:05:00,7:15:00,7:25:00]
我将非常感谢您的投入......
答案 0 :(得分:2)
我不完全确定这是否是您正在寻找的,但我会采取行动:
>>> indices = [index for index, i in enumerate(m) if i == 4]
>>> h = [d[i][0] for i in indices]
然后你必须按照自己的意愿处理timedeltas。
答案 1 :(得分:0)
deltas = [str(d[i][0]) for i, j in enumerate(m) if j == 4]
生成delta表示的列表作为字符串。
答案 2 :(得分:0)
所以每个索引都是timedeltas
的n元组吗?假设从代码中可能在每个索引处可能有多个timedelta
。
导入日期时间
import datetime
d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)}
m = [3, 4, 1, 4, 7, 4]
def something(m, d):
h = {}
for index in m:
if index in d and index not in h:
for dt in d[index]:
total = sum([dt.seconds for dt in d[index]])
hours = total / 3600
minutes = (total - (3600 * hours)) / 60
seconds = (total - (3600 * hours) - (60 * minutes))
h[index] = "%d:%02d:%02d" % (hours, minutes, seconds)
return h.values()
print something(m, d) # returns exactly what you asked for
答案 3 :(得分:-1)
你要求
吗?def hms( td ):
h = dt.seconds // 3600
m = dt.seconds%3600 // 60
s = dt.seconds%60
return h+td.days*24, m, s
[ hms(d[ m[i] ]) for i in m ]