Python 有人能解释一下为什么这个列表配对代码不起作用吗
我想知道列表中有多少对数字Python 有人能解释一下为什么这个列表配对代码不起作用吗,python,arrays,python-3.x,list,for-loop,Python,Arrays,Python 3.x,List,For Loop,我想知道列表中有多少对数字 ar=[10 ,20 ,20 ,10 ,10 ,30 ,50 ,10 ,20] 这是名单 我想得到输出3。因为有两对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 remov
ar=[10 ,20 ,20 ,10 ,10 ,30 ,50 ,10 ,20]
这是名单
我想得到输出3。因为有两对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笔记本,我再次运行此代码,输出为:
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 loop没有读取这个数字?在使用任何语言对其进行搜索时,决不要从列表中删除 一个简单的解决方法是使用列表理解并保留重要的内容
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
迭代时不要从列表中删除,无论第一行是否为反向(ar)中的i写入
,
,代码将从右侧开始向左移动。使用ar
列表的副本进行操作,并且仅使用ar
列表进行迭代:ar=[10,20,20,10,10,30,50,10,20]ar2=ar.copy()表示ar中的i:print(i)if ar2.count(i)%2:ar2.remove(i)print('removing..',i)print('number of pairs is:',len(ar2)//2)print('after the moving the double',ar2)
输出:10 20 removing。。20 20 10 30拆卸。。30 50删除。。50-10-20配对数为:3,去掉赔率[10,20,10,10,10,20]
当场。美好的但是,list.count
非常昂贵,-count(value)方法的时间复杂度对于一个包含n个元素的列表是O(n)。所以这个建议对于一个小的列表来说是很好的,如果列表是巨大的,可能会考虑-<代码>集合。