我正在迭代Python
中的元组列表,在我看来中间的元素似乎被跳过了。下面是我的代码块,目标是删除将None
作为第二个元素的任何元组:
print('List of tuples before modification: ' +str(list_of_tuples))
for refseq_tuple in list_of_tuples:
print('tuple: ' +str(refseq_tuple))
if refseq_tuple[1] == None:
list_of_tuples.remove(refseq_tuple)
print('List of tuples after modification: ' +str(list_of_tuples))
下面是输出:
List of tuples before modification: [('100652761', None), ('100653343', None), ('3183', 0)]
tuple: ('100652761', None)
tuple: ('3183', 0)
List of tuples after modification: [('100653343', None), ('3183', 0)]
那么…中间(第二)元素发生了什么?它看起来好像根本没有被迭代,或者它会在其他两个元组之间打印。你知道吗
正如其他人所指出的,您在迭代列表的同时修改它。但是,您可以通过一个列表理解来完成您正在做的事情(除非出于某种原因您确实需要进行适当的修改)。你知道吗
您已更改了原始列表。所以这次索引1引用
('3183', 0)
。你知道吗相关问题 更多 >
编程相关推荐