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]
總結
在本文中,我們瞭解瞭如何在輸入列表中列印負數的方法。
廣告