2021年4月3日星期六

Python basic question which i really cant understand the logic

def sum_five(l):      return sum(num for num in l if num > 5)  
#desired outcome:  #sum_five([1, 5, 20, 30, 4, 9, 18]) ➞ 77  #sum_five([1, 2, 3, 4]) ➞ 0  #sum_five([10, 12, 28, 47, 55, 100]) ➞ 252  

gotten this as a solution. The question is to loop through a list and sum up those that are less than 5. This is the cleanest and shortest answer which i really loved to learn. Can anyone explain in very simple English to me what does the num for num in l if num > 5 really means? And give me more examples to understand that logic so i can next time apply it? PS: i can do the outcome using for loop and if statement already, i just want to learn how to use this one liner. Thanks.

https://stackoverflow.com/questions/66937674/python-basic-question-which-i-really-cant-understand-the-logic April 04, 2021 at 11:03AM

没有评论:

发表评论