繁体   English   中英

在Python中使用循环修改列表:我的方法是否做错了?

[英]Modify list with loop in Python: Is my method of doing so wrong?

我刚刚开始学习Python,所以我只想弄清楚一点。 我想制作一个函数,该函数将列表“ lst”的当前最后三个元素的和重复添加到“ lst”,x个“ times”。 据我了解,您在迭代列表时不应更改列表,所以我的第二个解决方案是错误的,对吗? 即使产生与第一个函数相同的结果?

def appendsums(lst, times):
    count = 0
    for i in range(times):
        if count <= times:
            sums = sum(lst[-3:])
            lst.append(sums)
            count += 1
    return lst

这是我的第二个解决方案

def appendsums(lst, times):
    count = 0
    while count <= times:
        sums = sum(lst[-3:])
        lst.append(sums)
        count += 1
    return lst

问候

这通常是不安全的,因为不会通知容器上的迭代器已发生更改。 通常,您需要创建一个临时列表,然后在最后修改目标列表。

另外,作为补充,我想您可能希望计数小于次数(而不是等于)。

在当前形式下,当我将时间设置为5时,它将添加六个条目。

>>> def appendsums(lst, times):
...   count = 0
...   while count <= times:
...     sums = sum(lst[-3:])
...     lst.append(sums)
...     count += 1
...   return lst
... 
>>> appendsums([1,2,3], 5)
[1, 2, 3, 6, 11, 20, 37, 68, 125]

您是正确的,在编辑时不应遍历列表。 但是,正如其他用户指出的那样,以上示例均未遍历列表lst

这是迭代的示例:

for item in lst:
    # Do something

如果在编辑列表时需要遍历列表,请制作一个副本并遍历该副本:

copy_lst = lst[:]
for item in copy_lst:
     # edit lst

我会坚持以下代码:

def appendsums(lst, times):
    for i in range(times):
        lst.append(sum(lst[-3:]))
    return lst

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM