我在代码战中解决了一些kata,在当前的kata中,我试图得到一个元素在我设置为参数的列表中出现了多少次,然后用它作为for循环的范围
但是,当我调用函数时,它返回:
File "<pyshell#8>", line 3, in delete_nth
if order.count(item) > max_e:
AttributeError: 'NoneType' object has no attribute 'count'
这是我的密码
def delete_nth(order,max_e):
for item in order:
if order.count(item) > max_e:
for i in range(order.count(item) - max_e):
order = order.remove(item)
return order
l = [20,37,20,21]
delete_nth(l,1) #except [20,37,21]
问题是,即使在迭代过程中,您也在更改
order
。你不应该这样做。如果要创建现有列表的副本并对其进行修改remove
函数不返回任何内容,因此实际上没有任何内容被分配给order
问题在于这种说法
order = order.remove(item)
删除项目后不必重新分配列表。 并且list.remove也不返回任何导致错误的原因所以编辑如下:
order.remove(item)
相关问题 更多 >
编程相关推荐