简体   繁体   中英

how to iterate over a list containing multiple list and tuple

Iterate over a list conataining multiple list and tuple

pixel_coord=[]

[[(7261, 8764), (7288, 8764)], [(4421, 8937), (4448, 8937)]

increase 7261 by 7, decrease 7288 by 7 for the whole list.

I tried iterating list but don't know how to proceed

for p in range(len(pixel_coord)):
for i in range(4):
    print( pixel_coord[p][i][0] + 1)
    print( pixel_coord[p][i][1] - 1)
    i+=1
p+=1

Using a simple iteration & enumerate

Ex:

lst = [[(7261, 8764), (7288, 8764)], [(4421, 8937), (4448, 8937)]]
result = []
for i in lst:
    temp = []
    for ind, (x,y) in enumerate(i):
        if ind == 0:
            temp.append((x+7, y))
        else:
            temp.append((x-7, y))
    result.append(temp)

print(result)

Output:

[[(7268, 8764), (7281, 8764)], [(4428, 8937), (4441, 8937)]]
a= [[(7261, 8764), (7288, 8764)], [(4421, 8937), (4448, 8937)]]

def fun(a):
    k=[]
    for i in range(len(a)):
        if i%2==0:
            tmp=(a[i][0]+7,a[i][1])
            k.append(tmp)
        elif i%2==1:
            tmp=(a[i][0]-7,a[i][1])
            k.append(tmp)
    return k

sol= list(map(lambda x:fun(x), a))
print(sol)

output

[[(7268, 8764), (7281, 8764)], [(4428, 8937), (4441, 8937)]

This is how you can loop through your list of lists of tuples:

  temp = []
  for outerListIndex in range(len(pixel_coord)):
     for innerListIndex in range(len(pixel_coord[outerListIndex])):
        tupleElement1 = pixel_coord[outerListIndex][innerListIndex][0]
        tupleElement2 = pixel_coord[outerListIndex][innerListIndex][1]

        # Do your operations on the elements here
        temp.append( (tupleElement1 + 7, tupleElement2 - 7) )

  pixel_coord = temp

Once you properly name the variables your code becomes much easier to understand.

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