我是 Python 新手,我一直在用列表乱写。我只想打印列表中的正数,但是只有第一个负数元素被删除,第二个负数元素保持原样。
这是我的代码:
def myfunc(mylist1) :
print("List before sorting the elements : ", mylist1)
mylist1.sort()
print("List after sorting the elements : ", mylist1)
for i in range(0,len(mylist1)) :
if mylist1[i] <= 0 :
del mylist1[i]
else:
break
print("After Operations,Final list : ", mylist1)
return
mylist = [67,78,54,-20,-23,44]
myfunc(mylist)
输出:
List before sorting the elements : [67, 78, 54, -20, -23, 44]
List after sorting the elements : [-23, -20, 44, 54, 67, 78]
After Operations,Final list : [-20, 44, 54, 67, 78]
您可以通过列表理解删除它们。这是定义函数的方法:
def myfunc(mylist1):
return sorted([x for x in mylist1 if x > 0])
print(myfunc(mylist1))
我是一名优秀的程序员,十分优秀!