标签:str 速度 mic -- 表达 常用 阅读 zip 一行代码
列表做为python的基础,是必须学习的语法之一。一些基础的之前已经是反复温习和使用了,今天我们来学习它的进阶版--》列表推导式。
列表推导式:
[i for i in iterable if expression]
首先使用常用的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)
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)
要生成的元组如下:
[(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)
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)
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)
标签:str 速度 mic -- 表达 常用 阅读 zip 一行代码
原文地址:https://www.cnblogs.com/huny/p/14287918.html