问题是从数字中删除负数。
When remove_negs([1, 2, 3, -3, 6, -1, -3, 1])
执行后,结果为:[1, 2, 3, 6, -3, 1]
。结果应该是[1, 2, 3, 6, 3, 1]
。发生的情况是,如果连续有两个负数(例如,-1, -3
)那么第二个数字将不会被删除。
def main():
numbers = input("请输入数字列表:")
删除_否定(数字)
def remove_negs(num_list):
'''Remove the negative numbers from the list num_list.'''
for item in num_list:
if item < 0:
num_list.remove(item)
print num_list
main()
在迭代列表时从列表中删除元素通常是一个坏主意(请参阅the link在我的评论中解释为什么会这样)。更好的方法是使用列表理解:
num_list = [item for item in num_list if item >= 0]
请注意,上面的行创建了一个new列出并分配num_list
对此。您还可以对表单进行“就地”分配
num_list[:] = ...
它不会在内存中创建新列表,而是修改已指向的内存位置num_list
。更详细地解释了这种差异here.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)