>>> squares = [n**2 for n in range(5)]
>>> squares
[0, 1, 4, 9, 16]
>>> [4 for square in squares]
[4, 4, 4, 4, 4]
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
def count_negatives(nums):
return len([num for num in nums if num < 0])
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])
def has_lucky_number(nums):
return any([num % 7 == 0 for num in nums])
# 有一个True any 就得到 True
Loops and list
最新推荐文章于 2024-10-02 10:53:34 发布