简体   繁体   中英

how to sum adjacent tuples/list

I apologise for the terrible description and if this is a duplicated, i have no idea how to phrase this question. Let me explain what i am trying to do. I have a list consisting of 0s and 1s that is 3600 elements long (1 hour time series data). i used itertools.groupby() to get a list of consecutive keys. I need (0,1) to be counted as (1,1), and be summed with the flanking tuples.

so

[(1,8),(0,9),(1,5),(0,1),(1,3),(0,3)]

becomes

[(1,8),(0,9),(1,5),(1,1),(1,3),(0,3)]

which should become

[(1,8),(0,9),(1,9),(0,3)]

right now, what i have is

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 is a dictionary where the keys are filenames and the values are a list of numbers to be used in the function counter() . and this gives me something like this but much longer

[[1,8],[0,9],[1,5], [1,1], [1,3],[0,3]]

edits: solved it with the help of a friend,

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]

Not sure what exactly is that you need. But this is my best attempt of understanding it.

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)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM