迭代列表列表和元组列表

时间:2016-01-28 13:07:04

标签: python list for-loop

我试图同时迭代列表列表和元组列表,用列表列表中的值替换列表列表中的某些值。

到目前为止,这是我的代码:

tups = [(1,2,3),(4,5,6),(9,8,7)]

lsts = [[[1, 0, 1], [2, 3, 1, 0], [1, 1, 1, 1, 10, 0]], \
       [[1, 0, 1], [2, 3, 1, 0], [1, 1, 1, 1, 10, 0]], \
       [[1, 0, 1], [2, 3, 1, 0], [1, 1, 1, 1, 10, 0]]]


for index1, aitem in enumerate(tups):
    for index2, a in enumerate(aitem):
        for index3, mega_item in enumerate(lsts):
            for index4, bitem in enumerate(mega_item):
                for index5, b in enumerate(item):
                    if i == 0:
                        lsts[index3][index4][index5] = a
                        break
                    else:
                        continue
                    break
                else:
                    continue
                break
            else:
                continue
            break

我希望我的解决方案能够生成lsts,并按顺序将ts中的值替换为0,如下所示:

lsts = [[[1, 1, 1], [2, 3, 1, 2], [1, 1, 1, 1, 10, 3]], \
       [[1, 4, 1], [2, 3, 1, 5], [1, 1, 1, 1, 10, 6]], \
       [[1, 9, 1], [2, 3, 1, 8], [1, 1, 1, 1, 10, 7]]]

但是,我目前的结果是:

lsts = [[[1, 1, 1], [2, 3, 1, 2], [1, 1, 1, 1, 10, 3]], \
       [[1, 1, 1], [2, 3, 1, 2], [1, 1, 1, 1, 10, 3]], \
       [[1, 1, 1], [2, 3, 1, 2], [1, 1, 1, 1, 10, 3]]]

我相信我的循环可能只是迭代我的元组列表中的第一项。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

这应该有效:

for inner_lst,inner_tup in zip(lsts,tups):
   for ind,depth in enumerate(inner_lst):
          depth[depth.index(0)]= inner_tup[ind]

print lsts

输出:

[[[1, 1, 1], [2, 3, 1, 2], [1, 1, 1, 1, 10, 3]], 
 [[1, 4, 1], [2, 3, 1, 5], [1, 1, 1, 1, 10, 6]], 
 [[1, 9, 1], [2, 3, 1, 8], [1, 1, 1, 1, 10, 7]]]

答案 1 :(得分:1)

简单地嵌套for循环运行良好。

view trigger action --> 
store respond to actions --> 
store trigger changed -->
view respond to store(re-render in most case) --> 
view trigger action" 

输出:

for i in xrange(len(tups)):
 for j in xrange(len(tups[i])):
  index = lsts[i][j].index(0)
  lsts[i][j][index] = tups[i][j]

是:

for s in lsts:
 print s