前言
列表做为python的基础,是必须学习的语法之一。一些基础的之前已经是反复温习和使用了,今天我们来学习它的进阶版–》列表推导式。列表推导式:
- 优点:是将所有的值一次性加载到内存中,相比于for循环生成的列表执行速度快,并且语法精简,一行代码就完成for循环多行代码所要完成的事情。
- 缺点:代码的可阅读性就不太友好了语法:
[i for i in iterable if expression]
案例
###1. 列表推导式可以与 if 表达式结合首先使用常用的for循环实现
numbers = [-4, -3, -2, -1, 0, 2, 4, 6]listA = []for i in numbers:if i > 0:listA.append(i)print(listA)
下面请出列表推导式
numbers = [-4, -3, -2, -1, 0, 2, 4, 6]x = [x for x in numbers if x>0]print(x)
###2. 将以下二维列表展开成一维列表:
list_of_lists =[[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]l = [num for r in list_of_lists for num in r]s = [num for r in l for num in r]print(l)print(s)
###3. 使用列表推导式创建元组列表:要生成的元组如下:[(0, 1, 0, 0, 0, 0, 0),(1, 1, 1, 1, 1, 1, 1),(2, 1, 2, 4, 8, 16, 32),(3, 1, 3, 9, 27, 81, 243),(4, 1, 4, 16, 64, 256, 1024),(5, 1, 5, 25, 125, 625, 3125),(6, 1, 6, 36, 216, 1296, 7776),(7, 1, 7, 49, 343, 2401, 16807),(8, 1, 8, 64, 512, 4096, 32768),(9, 1, 9, 81, 729, 6561, 59049),(10, 1, 10, 100, 1000, 10000, 100000)]
s = [(i,1,i,i**2,i*i**2,i**4,i**2*i*i**2) for i in range(11)]print(s)
###4. 将多嵌套列表合并为一个新列表:
countries = [[(\'Finland\', \'Helsinki\')], [(\'Sweden\', \'Stockholm\')], [(\'Norway\', \'Oslo\')]]ls = [num for i in countries for num in i]ll = [num for i in ls for num in i]print(ll)
###5. 将列表更改为字典列表:
ll = []countries = [[(\'Finland\', \'Helsinki\')], [(\'Sweden\', \'Stockholm\')], [(\'Norway\', \'Oslo\')]]country = [\'country\',\'city\']ls = [num for i in countries for num in i]for i in ls:x = dict(zip(country, i))ll.append(x)print(ll)