列表生成式是一种基于其他 iterable(如集合、元组、其他列表等)创建列表的方法。它还可以用更简单、更吸引人的语法表示 for 和 if 循环
语法格式如:list = [expression for iterm in iterable (if conditional)]
- (if conditional) 中的 if 语句可有可无,但是前面的 expression 和 for 循环表达式必须存在
- 注意细节
- for 循环末尾的表达式放在列表的开头
1、实例如下:
words = ['data','science','machine','learning'] # 计算出 words 列表中每个字符串的长度 a = [] for word in words: a.append(len(word)) print(a) # 列表生成式做法 b = [len(word) for word in words] print(b) # 结果如下 [4, 7, 7, 8] [4, 7, 7, 8]
2、列表生成式中带有 if 语句实例如下:
words = ['data', 'science', 'machine', 'learning'] # 取出 words 列表中长度大于5的字符串长度 a = [] for word in words: if len(word) > 5: a.append(word) print(a) # 列表生成式做法 b = [word for word in words if len(word) > 5] print(b) # 结果如下 ['science', 'machine', 'learning'] ['science', 'machine', 'learning']
- 在列表生成式中带有多个 for 循环,表示 for 循环嵌套
words = ['data', 'science', 'machine', 'learning'] # 找出列表中所有字符串中的所有元音字母 a = [] for word in words: for letter in word: if letter in ["a","e","i","o","u"]: a.append(letter) print(a) # 列表生成式做法 b = [letter for word in words for letter in word if letter in ["a","e","i","o","u"]] print(b)
words = ['data', 'science', 'machine', 'learning'] # 找出列表中所有字符串中的所有元音字母,并将所有的元音字母进行大写 b = [letter.upper() for word in words for letter in word if letter in ["a","e","i","o","u"]] print(b) # 结果如下 ['A', 'A', 'I', 'E', 'E', 'A', 'I', 'E', 'E', 'A', 'I']
- 在列表生成式中传入调用函数
def func(x): return x * 2 s = [func(a) for a in range(5)] print(s) # 结果如下: [0, 2, 4, 6, 8]
标签:word,words,Python,生成式,列表,letter,print From: https://www.cnblogs.com/ZhengYing0813/p/16845777.html