如何遍历包含多个列表和元组的列表

时间:2019-05-02 09:27:49

标签: python list

遍历包含多个列表和元组的列表

pixel_coord=[]

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

整个列表将7261增加7,将7288减少7。

我尝试了迭代列表,但不知道如何进行

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

3 个答案:

答案 0 :(得分:1)

使用简单的迭代&enumerate

例如:

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)

输出:

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

答案 1 :(得分:0)

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)

输出

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

答案 2 :(得分:0)

这是如何遍历元组列表的列表:

  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

正确命名变量后,代码将更容易理解。