关联知识点:Python循环语句-for 循环
列表解析
根据已有列表,高效创建新列表的方式。
列表解析是Python迭代机制的一种应用,它常用于实现创建新的列表,因此用在[]中。
语法:
[expression for iter_val in iterable]
[expression for iter_val in iterable if cond_expr]
例:列出1~10所有数字的平方
>>> L = []
>>> for i in range(1, 11):
L.append(i ** 2)
>>> print (L)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 列表解析
>>> L = [ i**2 for i in range(1,11)] #[表达式 for 给表达式供值]
>>> print (L)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
例:列出1~10中大于等于4的数字的平方
>>> L = []
>>> for i in range(1, 11):
if i >= 4:
L.append(i ** 2)
>>> print(L)
[16, 25, 36, 49, 64, 81, 100]
# 列表解析
>>>L = [i**2 for i in range(1,11) if i >= 4] #[表达式 for 给表达式供值 if 值的条件]
>>>print(L)
[16, 25, 36, 49, 64, 81, 100]
例:列出1~10所有数字的平方除以2的值
>>> L = []
>>> for i in range(1, 11):
L.append(i ** 2 / 2)
>>> print(L)
[0.5, 2.0, 4.5, 8.0, 12.5, 18.0, 24.5, 32.0, 40.5, 50.0]
# 列表解析
>>> L = [i ** 2 / 2 for i in range(1, 11)]
>>> print(L)
[0.5, 2.0, 4.5, 8.0, 12.5, 18.0, 24.5, 32.0, 40.5, 50.0]
例:列出"/var/log"中所有已'.log'结尾的文件(转载,涉及到未知知识,未改写)
##################################################
1、普通方法
>>>import os
>>>file = []
>>> for file in os.listdir('/var/log'):
... if file.endswith('.log'):
... file.append(file)
...
>>> print file
['anaconda.ifcfg.log', 'Xorg.0.log', 'anaconda.storage.log', 'Xorg.9.log', 'yum.log', 'anaconda.log', 'dracut.log', 'pm-powersave.log', 'anaconda.yum.log', 'wpa_supplicant.log', 'boot.log', 'spice-vdagent.log', 'anaconda.program.log']
##################################################
2.列表解析
>>> import os
>>> file = [ file for file in os.listdir('/var/log') if file.endswith('.log') ]
>>> print file
['anaconda.ifcfg.log', 'Xorg.0.log', 'anaconda.storage.log', 'Xorg.9.log', 'yum.log', 'anaconda.log', 'dracut.log', 'pm-powersave.log', 'anaconda.yum.log', 'wpa_supplicant.log', 'boot.log', 'spice-vdagent.log', 'anaconda.program.log']
例:实现两个列表中的元素逐一配对
>>> L1 = ['x', 'y', 'z']
>>> L2 = [1, 2, 3]
>>> L3 = []
>>> for a in L1:
for b in L2:
L3.append((a, b))
>>> print(L3)
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
# 列表解析
>>> L1 = ['x','y','z']
>>> L2 = [1,2,3]
L3 = [ (a, b) for a in L1 for b in L2 ]
>>> print(L3)
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
例:使用列表解析生成 9*9 乘法表
>>> print('\n'.join([''.join(['%s*%s=%-2s ' % (y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)]))
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
例:检测新用户名列表是否在当前用户列表中,确保比较时不区分大小写。
current_users = ['John', 'TOM', 'cc', 'dd', 'ee']
new_users = ['tom', 'john', 'ff']
current_users_lower = [user.lower() for user in current_users] # 列表解析,等价代码如下注释
'''
current_users_lower = []
for user in current_users:
current_users_lower.append(user.lower())
'''
for new_user in new_users:
if new_user.lower() in current_users_lower:
print('用户名 '+ new_user +' 已被占用!')
else:
print('用户名 '+ new_user +' 可用!')
'''
用户名 tom 已被占用!
用户名 john 已被占用!
用户名 ff 可用!
'''
以下内容为堆砌,未整理,迟一些将列表、字典、集合的解析合并~~
集合推导式(Set comprehension)
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
python的各种推导式(列表推导式、字典推导式、集合推导式)
推导式comprehensions(又称解析式),是Python的一种独有特性。推导式是可以从一个数据序列构建另一个新的数据序列的结构体。 共有三种推导,在Python2和3中都有支持:
列表(list)推导式
字典(dict)推导式
集合(set)推导式
一、列表推导式
1、使用[]生成list
基本格式
variable = [out_exp_res for out_exp in input_list if out_exp == 2]
out_exp_res: 列表生成元素表达式,可以是有返回值的函数。
for out_exp in input_list: 迭代input_list将out_exp传入out_exp_res表达式中。
if out_exp == 2: 根据条件过滤哪些值可以。
例一:
multiples = [i for i in range(30) if i % 3 is 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
例二:
def squared(x):
return x*x
multiples = [squared(i) for i in range(30) if i % 3 is 0]
print multiples
# Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
2、使用()生成generator
将俩表推导式的[]改成()即可得到生成器。
multiples = (i for i in range(30) if i % 3 is 0)
print(type(multiples))
# Output: <type 'generator'>
二、字典推导式
字典推导和列表推导的使用方法是类似的,只不中括号该改成大括号。直接举例说明:
例子一:大小写key合并
复制代码
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
mcase_frequency = {
k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0)
for k in mcase.keys()
if k.lower() in ['a','b']
}
print mcase_frequency
# Output: {'a': 17, 'b': 34}
复制代码
例子二:快速更换key和value
mcase = {'a': 10, 'b': 34}
mcase_frequency = {v: k for k, v in mcase.items()}
print mcase_frequency
# Output: {10: 'a', 34: 'b'}
三、集合推导式
它们跟列表推导式也是类似的。 唯一的区别在于它使用大括号{}。
例一:
squared = {x**2 for x in [1, 1, 2]}
print(squared)
# Output: set([1, 4])