我如何修复两次追加列表



我在python上做了一个排序函数,但它写了两次"2",我该如何修复它?

liste = [10,200,5,2,3]
minimal = []
w = 0
try:
sayac = 0
lent= (len(liste)-1)
while True:
sayac += 1
if lent == sayac:
break
else:  
listelen = (len(liste)-1)
for i in liste:
if i <= liste[w] and i <= liste[listelen] and i <= liste[int(listelen/2)]:
minimal.append(i)
else:
pass
print(minimal)
lent = (len(minimal)-1)
for i in liste:
if i == minimal[lent]:
liste.remove(i)
else:
pass
except:
print(minimal)
OUT : [2, 3, 2, 5, 10, 200]
[2, 3, 2, 5, 10, 200]
...

我的"liste"值上有一个 2,但它写了两次我该如何修复它? 我的大脑现在不见了

因为您在第一步中添加了多个minimal,但随后仅从liste中删除最后一个:

liste = [10,200,5,2,3]
minimal = []
w = 0
try:
sayac = 0
lent= (len(liste)-1)
while True:
sayac += 1
if lent == sayac:
break
else:  
listelen = (len(liste)-1)
for i in liste:
if i <= liste[w] and i <= liste[listelen] and i <= liste[int(listelen/2)]:
minimal.append(i)
break ##########this line added
else:
pass
print(minimal)
lent = (len(minimal)-1)
for i in liste:
if i == minimal[lent]:
liste.remove(i)
else:
pass
except:
print(minimal)

此外,我会重新考虑打破条件,所以这可能会更好:

liste = [10,200,5,2,3]
minimal = []
w = 0
try:
sayac = 0
lent= (len(liste)-1)
while True:
sayac += 1
if len(liste)==0: ############condition changed
break
else:  
listelen = (len(liste)-1)
for i in liste:
if i <= liste[w] and i <= liste[listelen] and i <= liste[int(listelen/2)]:
minimal.append(i)
break #############this line added
else:
pass
print(minimal)
lent = (len(minimal)-1)
for i in liste:
if i == minimal[lent]:
liste.remove(i)
else:
pass
except:
print(minimal)

最新更新