简体   繁体   中英

summing together elements in list in python

I have two lists, t and e , of the same size: to each element t[i] corresponds an element e[i] . I want to print each pair t[i] e[i] , but summing together elements e[i] and e[i-1] whenever the corresponding t[i] and t[i-1] are closer than 1. In this case, elements e[5] and e[4] should be summed up, since the corresponding t[5]-t[4]<1 . The point is, I want to REPLACE the 4th elements with the 4th+5th elements, without printing the 5th elements. My code is:

t = [1, 5, 10, 16, 20, 21, 28, 33, 39, 42, 45, 50, 56]
e = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']

for j in range(1,12):
    if t[j]-t[j-1] <= 1:
        print t[j-1], e[j-1]+e[j]
    else:
        if t[j] > t[j-1]:
            print t[j-1], e[j-1]

But this gives me:

1 A
5 B
10 C
16 D
20 EF
21 F
28 G
33 H
39 I
42 J
45 K

I don't want to print 21 F , as it is already summed in the 20 EF . How can I do that? Is there a way to increase the counter i at the end of the if condition? Thank you in advance.

Another solution is a while loop :

t = [1, 5, 10, 16, 20, 21, 28, 33, 39, 42, 45, 50, 56]
e = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']

j = 1
while j < len(t):
    if t[j]-t[j-1] <= 1:
        print t[j-1], e[j-1]+e[j]
        j += 1
    else:
        if t[j] > t[j-1]:
            print t[j-1], e[j-1]
    j += 1

If it's just about the output:

for i in range(0, len(t)):
    if i<1:
        print( t[i], e[i], end="")
    else:
        if t[i] - t[i-1] > 1:
            print()
            print( t[i], e[i], end="")
        else:
            print( e[i], end="")

prints

1 A
5 B
10 C
16 D
20 EF
28 G
33 H
39 I
42 J
45 K
50 L
56 M

Either you use the solution down here or you look at this post: Skip over a value in the range function in python

t = [1, 5, 10, 16, 20, 21, 28, 33, 39, 42, 45, 50, 56]
e = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']

skip = False
for j in range(len(t)):
    if not skip:
        if t[j]-t[j-1] <= 1:
            print t[j-1], e[j-1]+e[j]
            skip = True
        else:
            if t[j] > t[j-1]:
                print t[j-1], e[j-1]
    else:
        skip = False

>1 A
>5 B
>10 C
>16 D
>20 EF
>28 G
>33 H
>39 I
>42 J
>45 K
>50 L

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