Python 如何对相邻元组/列表求和
我为这糟糕的描述道歉,如果这是重复的,我不知道如何表达这个问题。让我解释一下我想做什么。我有一个由0和1组成的列表,长度为3600个元素(1小时时间序列数据)。我使用Python 如何对相邻元组/列表求和,python,Python,我为这糟糕的描述道歉,如果这是重复的,我不知道如何表达这个问题。让我解释一下我想做什么。我有一个由0和1组成的列表,长度为3600个元素(1小时时间序列数据)。我使用itertools.groupby()来获取连续键的列表。我需要将(0,1)算作(1,1),并用两侧的元组求和 所以 变成 [(1,8),(0,9),(1,5),(1,1),(1,3),(0,3)] 应该变成什么 [(1,8),(0,9),(1,9),(0,3)] 现在,我所拥有的是 def counter(file):
itertools.groupby()
来获取连续键的列表。我需要将(0,1)算作(1,1),并用两侧的元组求和
所以
变成
[(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)]))
不确定你到底需要什么。但这是我理解它的最好尝试
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)]))
添加了我朋友的解决方案添加了我朋友的解决方案谢谢你的建议!但是我已经决定采用我朋友建议的方法,似乎很简短谢谢你的建议!但我已经决定采用我朋友建议的方法,似乎更短