Python 从列表中删除偶数
如何从列表中删除偶数Python 从列表中删除偶数,python,list,Python,List,如何从列表中删除偶数 a = [] i = 0 while i < 10: c = int(raw_input('Enter an integer: ')) a.append(c) i += 1 # this is the same as i = i + 1 for i in a: if i % 2 == 0: a.remove(i) print(a) 即使在输入了10之后,这仍然会要求输入数字。i被for语句
a = []
i = 0
while i < 10:
c = int(raw_input('Enter an integer: '))
a.append(c)
i += 1 # this is the same as i = i + 1
for i in a:
if i % 2 == 0:
a.remove(i)
print(a)
即使在输入了10之后,这仍然会要求输入数字。i被for语句重新分配。使用不同的变量。如果数字是偶数,为什么不阻止追加,而不是先添加然后检查删除
a = []
counter = 0
while counter < 10:
c = int(raw_input('Enter an integer: '))
if c % 2 != 0:
a.append(c)
counter += 1
print(a)
如果您想了解如何根据谓词“过滤”列表,下面是一个示例:
a_without_even = filter(lambda x: x%2==1, a)
像这样的
your_dirty_list = [2,3,3,3,4,4,2,2,7,7,8]
your_clean_list = [clean_dude for clean_dude in your_dirty_list if clean_dude % 2]
Out[]:[3,3,3,7,7]如果你把它们去掉,你会达到10岁吗?试着把它分成两部分。对不同的变量重复使用相同的变量名是一种糟糕的做法。把你的循环称为更具描述性的东西,比如计数器或类似的东西。最好尽快习惯你在第二个循环中重置i。您需要使用不同的变量。
your_dirty_list = [2,3,3,3,4,4,2,2,7,7,8]
your_clean_list = [clean_dude for clean_dude in your_dirty_list if clean_dude % 2]