[英]Comparing key-values in a dictionary as electrical usage per day
我有一個記錄特定建築物用電量的列表。 采樣每 30 分鍾進行一次。 我正在使用字典按天/月對樣本進行分組,之后我想我可以取每一天的最大值並減去第二天 - 前一天,這樣我就可以獲得當天的總數。 其中總量是千瓦時。
我遇到的一個問題是考慮第一天/第一個月的第一個最大值,因為我沒有什么可以比較的,因為那是第一個最大樣本? 如果有更好的方法請告訴? 我計划處理的方式是在那段時間內找到 min max 之間的差異,直到我獲得足夠的數據。
我創建了一個列表列表作為示例。 第一列將是月份和第二個記錄值。
下面顯示了按月份分組的字典,然后找到最大值。 您可以看到,一旦找到最大值和差異,就不會考慮第 1 個月嗎? 我應該得到的結果是 {1:4, 2:10, 3:25} ,這是按月總計,然后是 {1:39} 一年?
dict1 = {1: [1, 3, 4, 5], 2: [7, 8, 9, 10, 15], 3: [20, 25, 40]}
dict2 = {1: 5, 2: 15, 3: 40}
這是到目前為止的代碼,我注釋掉了操作以獲得年度和月份的總數,因為我的方法不起作用?
list1 = [[1, 1],
[1, 1],
[1, 0],
[1, 3],
[1, 4],
[1, 5], # max
[2, 7],
[2, 8],
[2, 9],
[2, 10],
[2, 15], # max
[3, 20],
[3, 25],
[3, 40]] # max
# using min/max of each day/month I'll miss the usage between the last value for the
# day/month and
# first value of next day/month.
# ex: day 1: 5 - 1 = 4 , day 2: = 9 - 7 = 2, day 3: 40 - 12 = 28
# missed usage from 5 to 7 and 9 to 12
# taking the difference between max values of each day/month
# ex: day 1: = 5, day 2: = 9, day 3 = 40 day 1 = 4, day 2 = 31
#
#
dict1 = {}
dict2 = {}
dict3 = {}
for i, j in list1:
if j > 0: # Samples will always be greater than zero so eliminate any sample that's not.
dict1.setdefault(i, []).append(j) # Group all the samples by day/month.
dict1[i] = sorted(list(set(dict1[i]))) # Check for duplicate samples
max_ = max(dict1[i])
dict2[i] = max_
print(dict1)
print(dict2)
您可以使用字典推導式執行您需要的操作:
list1
讀入dict1
:list1 = [[1, 1], [1, 1], [1, 0], [1, 3], [1, 4], [1, 5],
[2, 7], [2, 8], [2, 9], [2, 10], [2, 15],
[4, 20], [4, 25], [4, 40]]
months = sorted(set(l[0] for l in list1))
dict1 = {m: sorted(set(l[1] for l in list1 if l[0]==m and l[1]>0)) for m in months}
>>> dict1
{1: [1, 3, 4, 5], 2: [7, 8, 9, 10, 15], 4: [20, 25, 40]}
dict1
以獲得差異:您可以簡單地將索引 -1 和 0 用於最大值和最小值,因為列表是針對每個日期進行排序的。
dict2 = {m: dict1[m][-1]-dict1[m-1][-1] if m-1 in dict1 and dict1[m][0]>=dict1[m-1][-1] else dict1[m][-1]-dict1[m][0] for i, m in enumerate(months)}
>>> dict2
{1: 4, 2: 10, 4: 20}
dict2
獲取當年的總數:dict3 = {1: sum(dict2.values())}
>>> dict3
{1: 34}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.