Python列表推导式玩法
2021-03-06 20:29
标签:str 速度 mic -- 表达 常用 阅读 zip 一行代码 列表做为python的基础,是必须学习的语法之一。一些基础的之前已经是反复温习和使用了,今天我们来学习它的进阶版--》列表推导式。 首先使用常用的for循环实现 要生成的元组如下: Python列表推导式玩法 标签:str 速度 mic -- 表达 常用 阅读 zip 一行代码 原文地址:https://www.cnblogs.com/huny/p/14287918.html前言
列表推导式:
语法:[i for i in iterable if expression]
案例
1. 列表推导式可以与 if 表达式结合
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)
上一篇:Java特性和优势