我想知道列表中有多少对数字
ar=[10 ,20 ,20 ,10 ,10 ,30 ,50 ,10 ,20]
这是清单
我想得到输出 3。因为有 2 对 10 和一对 20
这是我的代码
for i in ar:
print(i)
if ar.count(i)%2:
ar.remove(i)
print('removing ..' ,i)
print('numbers of pairs is : ',len(ar)//2)
print('after removing the odds ',ar)
输出
10
20
removing .. 20
10
10
30
removing .. 30
10
20
numbers of pairs is : 3
after removing the odds [10, 20, 10, 10, 50, 10, 20]
为什么这段代码没有从列表中删除 50 ?
我正在使用 jupyter notebook,我再次运行此代码,输出为:
10
20
10
10
50
removing .. 50
20
numbers of pairs is : 3
after removing the odds [10, 20, 10, 10, 10, 20]
for 循环在第一次运行时没有从数组中读取 50。这就是为什么这段代码不起作用,我的问题是,为什么 for 循环没有读取这个数字?
答案 0 :(得分:1)
从不在迭代列表时从列表中删除,用我想说的任何语言。
一个简单的解决方案是使用列表理解并保留重要的内容
ar = [elt for elt in ar if not ar.count(elt) % 2]
想象一下 [1,2,4,5]
你想删除偶数,你会很容易看到你会错过你删除的元素之后的元素
forloop: cursor starts at 0
cursor on box 0 -> value 1 -> condition NOK
forloop: cursor moves to 1
cursor on box 1 -> value 2 -> condition OK -> remove value 2
forloop: cursor moves to 2
cursor on box 2 -> value 5 -> condition NOK