【问题标题】:Appending and Popping Items in a Python For Loop [duplicate]在 Python For 循环中追加和弹出项目 [重复]
【发布时间】:2022-01-23 07:54:12
【问题描述】:

我有一个大列表,我想将一半列表附加到 list1 和 list2,同时从原始列表中弹出项目。

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
 
list1 = []
list2 = []

for item in mylist:
    list1.append(mylist.pop())
    list2.append(mylist.pop())

    
list1
[8, 6, 4]
list2
[7, 5, 3]

为什么它没有遍历 mylist 中的整个列表?如果我通过添加项目来增加列表大小,它还会将更多项目追加/弹出到其他列表,但仍然不会完全遍历整个列表。

再次,我试图将原始列表的一半放入 list1,将原始列表的另一半放入 list2。

【问题讨论】:

    标签: python for-loop append


    【解决方案1】:

    在迭代时修改列表往往会混淆迭代。

    尝试这种方法,您不会迭代列表本身:

    >>> list1 = []
    >>> list2 = []
    >>> while mylist:
    ...     list1.append(mylist.pop())
    ...     list2.append(mylist.pop())
    ...
    >>> list1
    [8, 6, 4, 2]
    >>> list2
    [7, 5, 3, 1]
    

    或者:

    >>> mylist = [1, 2, 3, 4, 5, 6, 7, 8]
    >>> list1 = mylist[::-2]
    >>> list2 = mylist[-2::-2]
    >>> list1
    [8, 6, 4, 2]
    >>> list2
    [7, 5, 3, 1]
    

    【讨论】:

    • 谢谢。但为什么它不适用于 for 循环?我不明白为什么它没有通过列表。
    • 参见stackoverflow.com/questions/6260089/… 非常简短的解释是for 正在尝试根据您弹出项目之前的列表长度获取下一个索引,因此它失败并杀死了循环。
    猜你喜欢
    • 2020-10-10
    • 2014-11-19
    • 1970-01-01
    • 2016-09-13
    • 2014-07-30
    • 1970-01-01
    • 2018-10-04
    • 2017-02-12
    相关资源
    最近更新 更多