很抱歉,我的描述很糟糕,如果重复了,我不知道该如何表达这个问题。让我解释一下我要做什么。我有一个包含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]
答案 0 :(得分:0)
不确定您到底需要什么。但这是我理解它的最佳尝试。
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)]))