Python程序在列表中打印负数
在本文中,我们将学习解决给定问题陈述的解决方案和方法。
问题陈述
给定一个可迭代的列表,我们需要打印列表中的所有负数。
在这里,我们将讨论给定问题陈述的三种方法。
方法1-使用增强的for循环
示例
list1 = [-11,23,-45,23,-64,-22,-11,24]
# iteration
for num in list1:
# check
if num < 0:
print(num, end = " ")输出结果
-11 -45 -64 -22 -11
方法2-使用filter和lambda函数
示例
list1 = [-11,23,-45,23,-64,-22,-11,24]
# lambda exp.
no = list(filter(lambda x: (x < 0), list1))
print("Negative numbers in the list: ", no)输出结果
Negative numbers in the list: [-11 -45 -64 -22 -11]
方法3-使用列表理解
示例
list1 = [-11,23,-45,23,-64,-22,-11,24]
#list comprehension
nos = [num for num in list1 if num < 0]
print("Negative numbers in the list: ", nos)输出结果
Negative numbers in the list: [-11 -45 -64 -22 -11]
结论
在本文中,我们了解了在输入列表中打印负数的方法。
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短