迭代可能跳过elemen

2024-09-21 05:38:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在迭代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)]

那么…中间(第二)元素发生了什么?它看起来好像根本没有被迭代,或者它会在其他两个元组之间打印。你知道吗


Tags: ofnone元素列表list元组printafter
2条回答

正如其他人所指出的,您在迭代列表的同时修改它。但是,您可以通过一个列表理解来完成您正在做的事情(除非出于某种原因您确实需要进行适当的修改)。你知道吗

list_of_tuples = [tup for tup in list_of_tuples if tup[1] is not None]

您已更改了原始列表。所以这次索引1引用('3183', 0)。你知道吗

>>> alist = [('100652761', None), ('100653343', None), ('3183', 0)]
>>> [x for x in alist if not x[1] is None]
[('3183', 0)]
>>> 

相关问题 更多 >

    热门问题