给定一个数字列表, 编写一个Python程序以打印给定列表中的所有负数。
例子:
Input: list1 = [12, -7, 5, 64, -14]
Output: -7, -14
Input: list2 = [12, 14, -95, 3]
Output: -95
范例1:使用for循环打印给定列表中的所有负数
使用for循环遍历列表中的每个元素, 并检查number是否小于0。如果条件满足, 则仅打印数字。
# Python program to print negative Numbers in a List
# list of numbers
list1 = [ 11 , - 21 , 0 , 45 , 66 , - 93 ]
# iterating each number in list
for num in list1:
# checking condition
if num < 0 :
print (num, end = " " )
输出如下:
-21 -93
范例2:
使用while循环
# Python program to print negative Numbers in a List
# list of numbers
list1 = [ - 10 , 21 , - 4 , - 45 , - 66 , 93 ]
num = 0
# using while loop
while (num < len (list1)):
# checking condition
if list1[num] < 0 :
print (list1[num], end = " " )
# increment num
num + = 1
输出如下:
-10 -4 -45 -66
范例3:
使用
清单理解
# Python program to print negative Numbers in a List
# list of numbers
list1 = [ - 10 , - 21 , - 4 , 45 , - 66 , 93 ]
# using list comprehension
neg_nos = [num for num in list1 if num < 0 ]
print ( "Negative numbers in the list: " , * neg_nos)
输出如下:
Negative numbers in the list: -10 -21 -4 -66
范例4:
使用
Lambda表达式
# Python program to print negative Numbers in a List
# list of numbers
list1 = [ - 10 , 21 , 4 , - 45 , - 66 , 93 , - 11 ]
# we can also print negative no's using lambda exp.
neg_nos = list ( filter ( lambda x: (x < 0 ), list1))
print ( "Negative numbers in the list: " , * neg_nos)
输出如下:
Negative numbers in the list: -10 -45 -66 -11
注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。