Python 推导式是一种独特的数据处理方式,可以从一个数据序列构建另一个新的数据序列的结构体
1.列表推导式
[表达式 for 变量 in 列表]
[out_exp_res for out_exp in input_list]
或者
[表达式 for 变量 in 列表 if 条件]
[out_exp_res for out_exp in input_list if condition]
案例一:
计算非the 字符串的长度
sentence = "the quick brown fox jumps over the lazy dog" words = sentence.split() word_lengths = [len(word) for word in words if word != "the"] print(words) print(word_lengths)
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
[5, 5, 3, 5, 4, 4, 3]
案例二:
从列表"数字"中创建一个名为"newlist"的新列表,该列表仅包含列表中的正数,作为整数
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [int(x) for x in numbers if x > 0]
print(newlist)
2.字典推导式
{ key_expr: value_expr for value in collection }
或
{ key_expr: value_expr for value in collection if condition }
listdemo = ['Google','Runoob', 'Taobao'] # 将列表中各字符串值为键,各字符串的长度为值,组成键值对 newdict = {key:len(key) for key in listdemo} print(newdict)
{'Google': 6, 'Runoob': 6, 'Taobao': 6}
3.集合推导式
{ expression for item in Sequence }
或
{ expression for item in Sequence if conditional }
#求平方
setnew = {i**2 for i in (1,2,3)} print(setnew) {1, 4, 9}
4.元组推导式
(expression for item in Sequence ) 或 (expression for item in Sequence if conditional )