英文:
Removing the first element from a list inside a loop
问题
我正在创建一个函数,如果列表的第一个元素是偶数,则不断删除列表的第一个元素。以下是我尝试的代码,但第二个打印语句的输出仍然是一个包含10的列表:
def delete_starting_evens(lst):
for num in lst:
if lst[0] % 2 == 0:
lst.pop(0)
return lst
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
# [11, 12, 15]
print(delete_starting_evens([4, 8, 10]))
# [10]
期望/期望的结果:
[11, 12, 15]
[]
你想要翻译的部分已经完成。
英文:
I am creating a function to keep removing the first element of a list if its an even number
this is what i tried, but the outcome of the second print statement is still giving me a list with 10 inside it
def delete_starting_evens(lst):
for num in lst:
if lst[0] % 2 == 0:
lst.pop(0)
return lst
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
[11, 12, 15]
print(delete_starting_evens([4, 8, 10]))
[10]
expected/desired outcome:
[11, 12, 15]
[]
答案1
得分: 1
从正在迭代的列表中删除元素可能会产生副作用。请在原始列表的浅拷贝上进行迭代,并从原始列表中 原地 删除项。
以下是使用浅拷贝的示例(可以使用[:]
或调用copy()
方法):
def delete_starting_evens(lst):
for num in lst[:]:
if lst[0] % 2 == 0:
lst.pop(0)
return lst
英文:
Removing elements from the list you are iterating could have side effects.
Iterate over a shallow copy of the original list and remove terms, in-place, from the original one.
Here an example with shallow copy (either use [:]
or call the copy()
method)
def delete_starting_evens(lst):
for num in lst[:]:
if lst[0] % 2 == 0:
lst.pop(0)
return lst
答案2
得分: 1
另一种陈述这个问题的方式是,任何第一个奇数之前的偶数都应该被删除。
这意味着你只需要遍历列表,直到找到第一个奇数,而列表的其余部分保持不变。
这意味着如果找到一个奇数,循环可以提前退出,并返回在找到奇数的位置处切片的列表。
这样可以避免在迭代过程中修改正在迭代的列表的不良实践。
例如:
def delete_starting_evens(lst):
for idx, num in enumerate(lst):
if num % 2: # 如果找到奇数
return lst[idx:]
return [] # 列表中没有找到奇数,返回空列表
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
[11, 12, 15]
print(delete_starting_evens([4, 8, 10]))
[]
英文:
Another way of stating this problem is to say that any even number before the first odd number should be removed.
This means you only need to iterate through the list until you find the first odd number as the rest of the list remains unchanged.
This means the loop can exit early if an odd number is found returning a slice of the list at the point the odd number was found.
This avoids the bad practice of modifying the list that is currently being iterated over.
For example:
>>> def delete_starting_evens(lst):
... for idx, num in enumerate(lst):
... if num % 2: # if odd number found
... return lst[idx:]
... return [] # No odd numbers found in list, return empty list
>>> print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
[11, 12, 15]
>>> print(delete_starting_evens([4, 8, 10]))
[]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论