Python 2.7 为什么Python不';t将重复的列表迭代为一个列表
现在我正在研究Python2.7,我有一个小问题 我解释说,我需要将一个列表的索引放入另一个列表中:Python 2.7 为什么Python不';t将重复的列表迭代为一个列表,python-2.7,Python 2.7,现在我正在研究Python2.7,我有一个小问题 我解释说,我需要将一个列表的索引放入另一个列表中: students=[["A","B"],["A","B"]] for m in students: if "A" in m and "B" in m: print m 当我运行此代码时,我得到以下信息: ['A', 'B'] ['A', 'B'] 这似乎是对的,它在学生身上迭代并打印两次['A','B'],因为它是重复的…但是如果我运行以下代码: for m in
students=[["A","B"],["A","B"]]
for m in students:
if "A" in m and "B" in m:
print m
当我运行此代码时,我得到以下信息:
['A', 'B']
['A', 'B']
这似乎是对的,它在学生身上迭代并打印两次['A','B'],因为它是重复的…但是如果我运行以下代码:
for m in students:
if "A" in m and "B" in m:
print students.index(m)
它打印这个:
0
0
它似乎只在第一个元素上迭代,对我来说,正确的输出应该是这样的:
0
1
0
1
谁能解释一下Python为什么会这样做,以及如何修复它,谢谢学生们。索引(m)返回第一个索引,i
,其中students[i]
等于m
由于students
两次包含同一项,因此两次都返回0
因此循环在students
中迭代这两个项,但由于student[0]==student[1]
,当m
绑定到students[1]
时,students.index(student[1])
仍然返回0
如果只想报告循环的当前索引,请使用: 印刷品
0
1