python检查数字是否在嵌套列表中的某个位置

时间:2017-10-29 08:00:22

标签: python

testlist = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], [2,3,1,0,0], [3,0,1,2,0], [2,0,1,3,0]]

我想检查数字1是否在所有嵌套列表的第三列中,如果它应该将1替换为0,将该列表中的2替换为1。

提前致谢

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

testlist = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], [2,3,1,0,0],[3,0,1,2,0], [2,0,1,3,0]]
for ind,ele in enumerate(testlist):
    if ele[2] == 1:
        testlist[ind] = [i-1 if i in [1,2] else i for i in ele]

这应该给你输出如下

Input: testlist = [[1, 2, 3, 0, 0],
                   [0, 0, 3, 2, 1],
                   [1, 0, 0, 3, 2],
                   [2, 3, 1, 0, 0],
                   [3, 0, 1, 2, 0],
                   [2, 0, 1, 3, 0]]
Output: testlist -> [[1, 2, 3, 0, 0],
                     [0, 0, 3, 2, 1],
                     [1, 0, 0, 3, 2],
                     [1, 3, 0, 0, 0],
                     [3, 0, 0, 1, 0],
                     [1, 0, 0, 3, 0]]

答案 1 :(得分:-1)

为此,请将测试列表视为矩阵。您可以通过使用两个for循环来循环每个行和列来解决此问题。

testlist = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], [2,3,1,0,0], [3,0,1,2,0], [2,0,1,3,0]]

#traversing each row
for i, row in enumerate(testlist):
#traversing each column
   for j, c in enumerate(row):
   #in each column in the row check for '1', if found replace by '0'
      if j == 2 and c== 1:
         row[j] = 0
         #in the same row check for '2', if found replace my 1
         if 2 in row:
            ind = row.index(2)
            row[ind] = 1
print (testlist)