--- fid: 20240205-133748 url: https://www.w3schools.com/python/python_lists_comprehension.asp tags: list, list comprehension, comprehension --- # List Comprehension - A Short Guide [Python - List Comprehension](https://www.w3schools.com/python/python_lists_comprehension.asp) **难度**: 3 **时长**: 30 min ## Comprehension 用途 对(列表中的)每个成页应用相同的操作 ## 对 每个成员应用同一种操作 ### 问题: 将 names 中的每个名字改为大写 ``` names = ['alice', 'tom', 'bob'] ``` ### solution 1: (for in) ``` upper_names = [] for name in names: upper_names.append(name.upper()) ``` ### solution 2: map ``` upper_names = list(map(str.upper, names)) upper_names = list(map(lambda x: x.upper(), names)) ``` ### solution 3: comprehension ``` upper_names = [name.upper() for name in names] upper_names = (name.upper() for name in names) # iterable upper_names = list(upper_names) ``` ### 模式总结与语法 输出是 List,且针对成员做处理,完了之后,形成一个新的 List。 ```python newlist = [expression for item in iterable_list ``` **练习**: 如果是想把所有名字的字母逆序,该怎么实现?试一试 ## 条件过滤 ### 问题: 将包含了字符 `'a'` 的 list 成员找出来,形成一个新的 List: ```python fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) ``` ### if 这符合典型的 List Comprehension 特征,但需要加一个 if 条件: ```python fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] ``` ### 模式总结与语法 ```python newlist = [expression for item in iterable if condition == True] ``` The **return value** is a new list, leaving the old list unchanged. The **condition** is like a filter that only accepts the items that valuate to `True`. ## Examples ### 不作任何处理,原样复制 ```python newlist = [x for x in range(10)] ``` ### 对全体成员转大写 ```python newlist = [x.upper() for x in fruits] ``` ### filtering exclude | 排除 Only accept items that are not "apple" (filtering): ```python newlist = [x for x in fruits if x != "apple"] ``` ### 真假两种情况 (if else) ```python newlist = [x if x != "banana" else "orange" for x in fruits] ``` if 和 for 的位置不是固定的,当 if else 成对出现时,放在 for 前面; 否则 if 放在后面(只有过滤作用) ## 二维 comprehension 用 comprehension 计算 9x9 乘法表中的所有计算结果,共 81 个乘法 ### for in 写法 ``` for i in a: for j in b: c.append(i*j) ``` ### 2d comprehension ``` a = range(1, 10) b = range(1, 10) c = [i * j for i in a for j in b] print(c) len(c) ``` 要点:两个 for 是顺序写法 ### 带 if 条件(三角形) ``` c = [i*j for i in a for j in b if i <= j] ```