gpt4 book ai didi

python - 如何从 Python 列表中删除负数?

转载 作者:太空宇宙 更新时间:2023-11-03 19:55:27 25 4
gpt4 key购买 nike

我是 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))

关于python - 如何从 Python 列表中删除负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59563734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com