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]
结论
在本文中,我们了解了在输入列表中打印负数的方法。
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便