python检查一个数字是否在嵌套列表中的某个位置
我想检查数字1是否在所有嵌套列表的第三列中,如果在第三列中,则应将该列表中的1替换为0,将该列表中的2替换为1 提前感谢您可以尝试以下方法:python检查一个数字是否在嵌套列表中的某个位置,python,Python,我想检查数字1是否在所有嵌套列表的第三列中,如果在第三列中,则应将该列表中的1替换为0,将该列表中的2替换为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]] 这将为您提供如下输出 testlist = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], [2
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]]
这将为您提供如下输出
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]
为此,将TestLIST视为矩阵。您可以通过使用两个for循环来循环每一行和每一列来解决这个问题
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]]
那么,你是如何解决这个问题的呢?另外,不要用
list
来命名列表。主要是我不知道怎么做。是什么阻止了你阅读文档和学习?我必须导入任何东西吗,这里使用的所有内容都来自标准库和python构建-ins@ParthVerma它用零替换1,而不是用1替换2。@JoeJunior我以为你只想替换那个。必须在问题“列表中的2加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]]
#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)