定義一個函數(shù)計算列表中小于零的元素數(shù)量。大家看一下不同的思路嘱根,應(yīng)該還是很有啟發(fā)的嚣潜。
不使用循環(huán)的方法
def count_negatives(nums):
"""Return the number of negative numbers in the given list.
>>> count_negatives([5, -1, -2, 0, 3])
2
"""
nums.append(0)
nums.sort()
return nums.index(0)
使用循環(huán)的方法 1
def count_negatives(nums):
"""Return the number of negative numbers in the given list.
>>> count_negatives([5, -1, -2, 0, 3])
2
"""
n_negative = 0
for num in nums:
if num < 0:
n_negative = n_negative + 1
return n_negative
使用循環(huán)的方法 2
def count_negatives(nums):
return len([num for num in nums if num < 0])
使用循環(huán)的方法 3
def count_negatives(nums):
# Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of
# Python where it calculates something like True + True + False + True to be equal to 3.
return sum([num < 0 for num in nums])
這個算法很有趣唤锉,利用True==1的特性進(jìn)行計算世囊。
以上三個方法哪一個是最好的是一個很主觀的判斷。用更少的代碼解決問題總是好的窿祥,但Python的哲學(xué) The Zen of Python也不要忘了:
Readability counts. 需要考慮易讀性株憾。
Explicit is better than implicit. 一目了然的要比晦澀的更好。
內(nèi)容參考了Kaggle上的內(nèi)容(https://www.kaggle.com/colinmorris/loops-and-list-comprehensions)