简体   繁体   中英

Iterate over two lists

I want to iterate over 2 lists, and compare elements from the same list to see if higher or lower. something like

high = [5,7,8,4,2... 3] low = [16,4,8,1,48... 4]

if number in high > than previous number, add it to the high_list if number in low < previous number, add it to the low_list

output would be

high_list = [5,7,8] low_list = [16,4,1]

def iter_num (high,low):
    some_listH = []
    some_listL = []
    for H,L in zip(high,low):
        x = H +1
        if H > H[x]:
            H = H[x]
            some_listH.append(H)
        if L < L[x]:
            L = L[x]
            some_listL.append(L)
        return some_listH, some_listL

You have written:

 H > H[x]

Either H is an element of a list, or it is a list. It is not both.

The two lists essentially have nothing to do with eachother. If they are not guaranteed to be the same length, I would not recommend handling them in the same loop.

This should do what you want for one list. You can figure out from this how you want to handle the second list, put it into a function, etc.

list = [5,7,8,4,2,1,1,1,3]
some_listL = []

some_listL.append(list[0])
for x, y in zip(list, list[1:]):
    if y > x:
        some_listL.append(y)

print (some_listL)

To give credit where credit is due, I learned how to do this from here

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