[英]how to sum adjacent tuples/list
對於糟糕的描述,我深表歉意,如果重復的話,我也不知道如何表達這個問題。 讓我解釋一下我要做什么。 我有一個包含0和1的列表,它們的長度為3600個元素(1小時時間序列數據)。 我使用itertools.groupby()
來獲取連續鍵的列表。 我需要將(0,1)計為(1,1),並與側面的元組相加。
所以
[(1,8),(0,9),(1,5),(0,1),(1,3),(0,3)]
變成
[(1,8),(0,9),(1,5),(1,1),(1,3),(0,3)]
應該變成
[(1,8),(0,9),(1,9),(0,3)]
現在,我所擁有的是
def counter(file):
list1 = list(dict[file]) #make a list of the data currently working on
graph = dict.fromkeys(list(range(0,3601))) #make a graphing dict, x = key, y = value
for i in list(range(0,3601)):
graph[i] = 0 # set all the values/ y from none to 0
for i in list1:
graph[i] +=1 #populate the values in graphing dict
x,y = zip(*graph.items()) # unpack graphing dict into list, x = 0 to 3600 and y = time where it bite
z = [(x[0], len(list(x[1]))) for x in itertools.groupby(y)] #make a new list z where consecutive y is in format (value, count)
z[:] = [list(i) for i in z]
for i in z[:]:
if i == [0,1]:
i[0]=1
return(z)
dict
是一個字典,其中的鍵是文件名,值是要在功能counter()
使用的數字的列表。 這給了我類似的東西,但時間更長
[[1,8],[0,9],[1,5], [1,1], [1,3],[0,3]]
編輯:在朋友的幫助下解決了這個問題,
while (0,1) in z:
idx=z.index((0,1))
if idx == len(z)-1:
break
z[idx] = (1,1+z[idx-1][1] + z[idx+1][1])
del z[idx+1]
del z[idx-1]
不知道您到底需要什么。 但這是我理解它的最佳嘗試。
def do_stuff(original_input):
new_original = []
new_original.append(original_input[0])
for el in original_input[1:]:
if el == (0, 1):
el = (1, 1)
if el[0] != new_original[-1][0]:
new_original.append(el)
else:
(a, b) = new_original[-1]
new_original[-1] = (a, b + el[1])
return new_original
# check
print (do_stuff([(1,8),(0,9),(1,5),(0,1),(1,3),(0,3)]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.