我正在尝试将durationdictionary
格式化为每个唯一元素得到(小时:分钟:秒)。字典中有7个唯一的数字。
以下是durationdictionary
的示例:有人可以告诉我如何执行此操作。 (格式为{Phonenumber : Total seconds}
)
{'7807890123': 129370, '7803214567': 179532, '7808907654': 121726, '7809876543': 190211}
这是我的代码:
def call_list():
list =[line.strip().split(";") for line in calls_file]
#Gets the total amount of seconds for each unique user in the list.
for i in list:
duration = int(i[3])
if i[1] in durationdictionary.keys():
durationdictionary[i[1]] += duration
else:
durationdictionary[i[1]] = duration
# Gets the total amount of seconds from each individual in the dictionary called durationdictionary at index 1 and converts in into the format (h:m:s)
for i in list:
min_t = math.floor(durationdictionary[i[1]]//60)
second = math.floor(durationdictionary[i[1]]//60)
minute = min_t//60
hour = minute//60
durationdictionary[i[1]] = str(hour) + "h" + str(minute) + "m" + str(second) + "s"
print(durationdictionary)
答案 0 :(得分:1)
要将秒数分为小时,分钟和秒,我建议您反复使用divmod
。调用divmod(a, b)
会返回一个2元组,(a//b, a%b)
(计算它们可能比自己使用两个运算符更有效):
minutes, seconds = divmod(durationdictionary[i[1]], 60)
hours, minutes = divmod(minutes, 60)
我认为还有另一个问题,因为您正在迭代list
以获取i
,但修改durationdictionary
的方式可能会导致items()
。重复(您将值从整数转换为字符串。您可能希望迭代字典' durrationdictionary
,或者可能只是构建一个新字典而不是修改字典的值现有的。
这里有一些更新for phone_number, seconds in durationdictionary.items():
minutes, seconds = divmod(seconds, 60)
hours, seconds = divmod(minutes, 60)
durationdictionary[phone_number] = "{}h{}m{}s".format(hours, minutes, seconds)
的代码,使用上述逻辑转换时间:
$(document).ready(function() {
$(".product_id").blur(function() {
var value = $(".product_id").val()
$.ajax({
type: 'GET',
url: 'product_prices/' + 'value' ,
success: function (data) {
console.log('success', data)
}
});
});
});