我做了这个功能,可以从列表中删除所有的奇数。 (我无法修改原始列表)
代码:-
def purify(sequence):
purified = sequence
for i in purified:
if i % 2 != 0:
purified.remove(i)
return purified
该函数适用于大多数列表,但是如果列表具有与[4, 5, 5, 4]
类似的值,则它将返回[4, 5, 4]
。
我已经更改了代码以实现所需的功能,但我很好奇为什么会发生这种情况?
答案 0 :(得分:2)
您不应在迭代时尝试删除元素。另外,purified = sequence
实际上并没有创建sequence
的副本。最好的方法是像这样使用列表理解:
def purify(sequence):
purified = [i for i in sequence if i % 2 == 0]
return purified
答案 1 :(得分:2)
purified = sequence
不会创建sequence
的副本并分配给purified
,而是两个变量都指向您要尝试的同一个对象。此外,您还修改了要迭代的相同列表,因此行为很奇怪。
您有几种选择,它们都可以在Python 2.7上运行
sequence[:]
复制序列的副本,称为列表拼接,然后对其进行迭代def purify(sequence):
#Iterate on copy of sequence
for i in sequence[:]:
if i % 2 != 0:
sequence.remove(i)
return sequence
print purify([4, 5, 5, 4])
#[4, 4]
def purify(sequence):
#Pick only even values
return [item for item in sequence if item%2 == 0]
print purify([4, 5, 5, 4])
#[4, 4]
filter
过滤出奇数值def purify(sequence):
# Iterate on copy of sequence
return list(filter(lambda x:x%2==0, sequence))
print(purify([4, 5, 5, 4]))
# [4, 4]
答案 2 :(得分:1)
(我可以发誓要回答这个问题,但我找不到...)
无论如何,原因是您在迭代序列时正在修改序列。您应该改为执行以下操作:
# Python 3
def purify(sequence):
purified = sequence.copy()
for i in sequence:
if i % 2 != 0:
purified.remove(i)
return purified
# Python 2
from copy import copy
def purify(sequence):
purified = copy(sequence)
for i in sequence:
if i % 2 != 0:
purified.remove(i)
return purified
或者,您可以从空的list
开始,然后添加满足条件的元素:
def purify(sequence):
purified = []
for i in sequence:
if i % 2 == 0:
purified.append(i)
return purified
或者,通过list
的理解,这是
purified = [i for i in sequence if i % 2 == 0]
答案 3 :(得分:1)
在python2.7上,使用copy
模块。
例如:
from copy import copy
def purify(sequence):
purified = copy(sequence)
for i in sequence:
if i % 2 != 0:
purified.remove(i)
return purified
print purify([4, 5, 5, 4])
答案 4 :(得分:0)
通过使用 filter
# python 2.x
your_list= filter(lambda x: x % 2 == 0, your_list)
# python 3.x
your_list = list(filter(lambda x: x % 2 == 0, your_list))
print(your_list)
说明:
欢呼!