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 恩师诗词祝福语简短大全