Python程式中列表中正數和負數的計數


在本文中,我們將學習下面給出的問題陳述的解決方案。

問題陳述 - 給定一個列表可迭代物件,我們需要計算其中的正數和負數,並顯示它們。

方法 1 - 使用迭代結構(for)的暴力方法

這裡我們需要使用 for 迴圈迭代列表中的每個元素,並檢查 num>=0,以過濾正數。如果條件計算結果為真,則增加 pos_count,否則增加 neg_count。

示例

即時演示

list1 = [1,-2,-4,6,7,-23,45,-0]
pos_count, neg_count = 0, 0
# enhanced for loop  
for num in list1:
   # check for being positive
   if num >= 0:
      pos_count += 1
   else:
      neg_count += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)

輸出

Positive numbers in the list: 5
Negative numbers in the list: 3

方法 2 - 使用迭代結構(while)的暴力方法

這裡我們需要使用 for 迴圈迭代列表中的每個元素,並檢查 num>= 0,以過濾正數。如果條件計算結果為真,則增加 pos_count,否則增加 neg_count。

示例

即時演示

list1 = [1,-2,-4,6,7,-23,45,-0]
pos_count, neg_count = 0, 0
num = 0
# while loop
while(num < len(list1)):
   # check
   if list1[num] >= 0:
      pos_count += 1
   else:
      neg_count += 1
   # increment num
   num += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)

輸出

Positive numbers in the list: 5
Negative numbers in the list: 3

方法 3 - 使用 Python Lambda 表示式

在這裡,我們藉助 filter 和 lambda 表示式,可以直接區分正數和負數。

示例

即時演示

list1 = [1,-2,-4,6,7,-23,45,-0]
neg_count = len(list(filter(lambda x: (x < 0), list1)))
pos_count = len(list(filter(lambda x: (x >= 0), list1)))
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)

輸出

Positive numbers in the list: 5
Negative numbers in the list: 3

所有變數都在區域性作用域中宣告,並且它們的引用在上面的圖中可見。

結論

在本文中,我們學習瞭如何在列表中計算正數和負數。

更新於:2020-07-11

4K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.