kaggle教程--python基础

循环和列表推导式(Loops and List Comprehensions)

 

例1:求列表的平方

squares = [n**2 for n in range(10)]
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 

例2:求列表中字母少于6的单词

short_planets = [planet for planet in planets if len(planet) < 6]
short_planets
['Venus', 'Earth', 'Mars']

 

例3:求列表中字母少于6的单词,并在每个单词后面加!

loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6]
loud_short_planets
['VENUS!', 'EARTH!', 'MARS!']

 

例4:明白列表推导式的意思

[32 for planet in planets]
[32, 32, 32, 32, 32, 32, 32, 32]

 

例5:求一个列表中负数的个数

def count_negatives(nums):
  return len([num for num in nums if num < 0])

posted on 2019-02-27 10:57  wangzhonghan  阅读(178)  评论(0)    收藏  举报

导航