master
/ 6.2.6 列表推导式.ipynb

6.2.6 列表推导式.ipynb @masterview markup · raw · history · blame

Notebook

推导式

推导式(comprehensions)又称解析式,可以从一个数据序列构建另一个新的数据序列的结构体。 推导式是Python的一种独有特性,本质上可以将其理解成一种集合了变换和筛选功能的函数,通过这个函数把一个序列转换成另一个序列。

共有三种推导式:
列表(list)推导式
字典(dict)推导式
集合(set)推导式

本节学习列表推导式。 列表推导式是一种创建新列表的便捷的方式,通常用于根据一个列表中的每个元素通过某种运算或筛选得到另外一系列新数据,创建一个新列表。

列表推导式由1个表达式跟一个或多个for 从句、0个或多个if从句构成。 for前面是一个表达式,in 后面是一个列表或能生成列表的对象。将in后面列表中的每一个数据作为for前面表达式的参数,再将计算得到的序列转成列表。if是一个条件从句,可以根据条件返回新列表。

例如,计算0-9中每个数的平方,存储于列表中输出,可以用以下方法实现:

In [1]:
squares = []               # 创建空列表squares
for x in range(10):        # x依次取0-10中的数字
    squares.append(x**2)   # 向列表中增加x的平方
print(squares)       # 输出列表squares,[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#用lambda函数实现,将0-9中每个数映射为其平方并转为列表
squares = list(map(lambda x: x**2, range(10)))   
print(squares)       # 输出列表squares,[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

也可以用列表推导式来实现:

In [5]:
squares = [x**2 for x in range(10) if x%2 == 0]#计算range(10)中每个数的平方,推导出新列表
print(squares)      # 输出新列表squares,[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 4, 16, 36, 64]

[x ** 2 for x in range(10)]是一个列表推导式,推导式生成的序列放在列表中,for 从句前面是一个表达式,in 后面是一个列表或能生成列表的对象。将in后面列表中的每一个数据作为for前面表达式的参数,再将计算得到的序列转成列表。可以发现,用列表推导式实现的代码更简洁。

for前面也可以是一个内置函数或自定义函数,例如:

In [6]:
def fun(x):
    return x + x ** 2 + x ** 3     # 返回x + x ** 2 + x ** 3

y = [fun(i) for i in range(10)]    # 列表推导式,按函数fun(x),推导出新列表
print(y)               # 输出列表[0, 3, 14, 39, 84, 155, 258, 399, 584, 819]
[0, 3, 14, 39, 84, 155, 258, 399, 584, 819]

列表推导式还可以用条件语句(if从句)对数据进行过滤,用符合特定条件的数据推导出新列表,例如:

In [8]:
def fun(x):
    return x + x**2 + x ** 3  # 返回x + x ** 2 + x ** 3

# 列表推导式,根据原列表中的偶数,推导新列表
y = [fun(i) for i in range(10) if i%2 == 0]  
print(y)                                     # 输出列表[0, 14, 84, 258, 584]
[0, 14, 84, 258, 584]

可以用多个for从句对多个变量进行计算,例如:

In [9]:
ls = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
print(ls)      # 输出[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

in 后面也可以直接是一个列表,例如:

In [ ]:
ls = [-4, -2, 0, 2, 4]
print([x*2 for x in ls])# 将原列表每个数字乘2,推导出新列表 [-8, -4, 0, 4, 8]
print([x for x in ls if x >= 0])   # 过滤列表,返回只包含正数的列表[0, 2, 4]
print([abs(x) for x in ls])        # 应用abs()函数推导新列表[4, 2, 0, 2, 4]
# 调用strip()方法去除每个元素前后的空字符,返回['banana', 'apple', 'pear']
freshfruit = ['  banana', '  apple ', 'pear  ']
print([fruit.strip() for fruit in freshfruit]) #
# 生成一个每个元素及其平方(number, square)构成的元组组成的列表
print([(x, x**2) for x in range(6)]) 
# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

车牌限行是看尾号单双,末尾为字母时看倒数第一个非字母的数字:

In [ ]:
# 鄂A.27F37
# 鄂A.2737F
license_plate = input()

# 鄂A.27F37->2737
license_plate_int = int(''.join([x for x in license_plate if x.isdigit()]))
if license_plate_int % 2 == 0:
    print('限行')
else:
    print('允许通行')

从文章中筛选字符

In [8]:
txt = '''
I Want Nothing 我一无所求

Tagore 泰戈尔



I asked nothing, 

only stood at the edge of the wood behind the tree.  

我一无所求,

只站在林边树后。 

Languor was still upon the eyes of the dawn, 

and the dew in the air.  

倦意还逗留在黎明的眼上,

露润在空气里。 

The lazy smell of the damp grass hung in the thin mist above the earth.  

湿草的懒味悬垂在地面的薄雾中。 

Under the banyan tree you were milking the cow with your hands,

 tender and fresh as butter.  

在榕树下你用乳油般柔嫩的手挤着牛奶。 

And I was standing still.  

我沉静地站立着。  



I did not come near you.  

我没有走近你。  

The sky woke with the sound of the gong at the temple.  

天空和庙里的锣声一同醒起。  



The dust was raised in the road from the hoofs of the driven cattle.  

街尘在驱走的牛蹄下飞扬。  



With the gurgling pitchers at their hips, 

women came from the river.  

把汩汩发响的水瓶搂在腰上,

女人们从河边走来。 

Your bracelets were jingling, 

and foam brimming over the jar.  

你的钏镯丁当,

乳沫溢出罐沿。 

The morning wore on and I did not come near you.  

晨光渐逝而我没有步近你。
'''

txt_en = ''.join([c for c in txt if ord(c)<128])
print(txt_en)

葡萄酒数据分析: /data/bigfiles/winemag-data.csv

In [ ]:
# 先得到二维列表
[[0, 'Italy', "Aromas include tropical fruit, broom, brimstone and dried herb. The palate isn't overly expressive, offering unripened apple, citrus and dried sage alongside brisk acidity.", 87, 13.0, 'Sicily & Sardinia'], 
 [10, 'US', 'Soft, supple plum envelopes an oaky structure in this Cabernet, supported by 15% Merlot. Coffee and chocolate complete the picture, finishing strong at the end, resulting in a value-priced wine of attractive flavor and immediate accessibility.', 87, 19.0, 'California'], 
 [20, 'US', 'Ripe aromas of dark berries mingle with ample notes of black pepper, toasted vanilla and dusty tobacco. The palate is oak-driven in nature, but notes of tart red currant shine through, offering a bit of levity.', 87, 23.0, 'Virginia'], 
 [30, 'France', 'Red cherry fruit comes laced with light tannins, giving this bright wine an open, juicy character.', 86, 15.0, 'Beaujolais'], 
 [40, 'Italy', "Catarratto is one of Sicily's most widely farmed white grape varieties. This expression shows a mineral note, backed by citrus and almond blossom touches.", 86, 17.0, 'Sicily & Sardinia'],
 [50, 'Italy', "This blend of Nero d'Avola and Syrah opens with savory aromas of cured meat, dried berry, cassis, tobacco and wet earth. There's a touch of almond bitterness on the finish.", 86, 15.0, 'Sicily & Sardinia'], 
 [60, 'US', 'Syrupy and dense, this wine is jammy in plum and vanilla, with indeterminate structure and plenty of oak. Ripe and full-bodied, it has accents of graphite and leather.', 86, 100.0, 'California'], 
 [70, 'US', 'Aromas of vanilla, char and toast lead to light creamy stone fruit and canned-corn flavors. It provides appeal but the oak seems overweighted.', 86, 12.0, 'Washington'],
 [80, 'Chile', 'Caramelized oak and vanilla aromas are front and center on a barrel-heavy nose. This feels a bit choppy, with astringent tannins. Herbal salty plum flavors wear a lot of oaky makeup, while this finishes with a forced woody flavor.', 86, 12.0, 'Rapel Valley'], 
 [90, 'US', "This blend of Sangiovese, Malbec, Cabernet Sauvignon, Petite Sirah and other varieties plays well to type. It shows a wealth of ripe, dusty black fruit that's richly round and soft on the palate, approachable and lightly oaked.", 88, 23.0, 'California']
]
In [10]:
import pandas as pd
import math

df = pd.read_csv('images/ch6/winemag-data.csv')
wine_ls = df.values.tolist()  # 得到数据的二维列表
# print(wine_ls[:3])  # 查看二维列表

# 1. 用列表推导式,得到所有的国家列表
countries = [i[1] for i in wine_ls]
print(countries[:10])
print(set(countries))
print(sorted(set(countries)))

# 2. 用列表推导式,得到所有的酒的评分的平均分
points = [i[3] for i in wine_ls if not math.isnan(i[4])]
print(sum(points) / len(points))

# 3. 用列表推导式,得到所有的酒的价格的平均价
prices = [i[4] for i in wine_ls if not math.isnan(i[4])]
print(sum(prices) / len(prices))
['Italy', 'US', 'US', 'France', 'Italy', 'Italy', 'US', 'US', 'Chile', 'US']
{'Austria', 'Slovenia', 'Lebanon', 'Portugal', 'Bulgaria', 'Israel', 'Chile', 'Argentina', 'Peru', 'Mexico', 'Brazil', 'Morocco', 'Greece', 'Ukraine', 'Croatia', 'Germany', 'Armenia', 'Spain', 'Hungary', 'France', 'South Africa', 'Uruguay', 'Romania', 'Cyprus', 'US', 'Moldova', 'Italy', 'Georgia', 'England', 'Luxembourg', 'Australia', 'Canada', 'Turkey', 'New Zealand', 'Czech Republic', 'Switzerland'}
['Argentina', 'Armenia', 'Australia', 'Austria', 'Brazil', 'Bulgaria', 'Canada', 'Chile', 'Croatia', 'Cyprus', 'Czech Republic', 'England', 'France', 'Georgia', 'Germany', 'Greece', 'Hungary', 'Israel', 'Italy', 'Lebanon', 'Luxembourg', 'Mexico', 'Moldova', 'Morocco', 'New Zealand', 'Peru', 'Portugal', 'Romania', 'Slovenia', 'South Africa', 'Spain', 'Switzerland', 'Turkey', 'US', 'Ukraine', 'Uruguay']
88.42847747451496
36.42773758632029
In [ ]:
 

练一练

实例 6.2 中读取文件中数据到列表的操作用列表推导式来实现会变得更为简洁。

In [ ]:
scores = []                      # 创建空列表
with open('5.1 score.txt','r',encoding='utf-8') as data:
   for line in data:             # 遍历文件对象
      scores.append(int(line.strip().split()[1]))      
print(scores)                    # 输出列表

# 列表推导式实现
with open('5.1 score.txt','r',encoding='utf-8') as data:
   scores = [int(line.strip().split()[1]) for line in data]
print(scores)                    # 输出列表

实例 6.3 自幂数 自幂数是指一个 n 位数,它的每个位上的数字的 n 次幂之和等于它本身,例如:153 = 13 + 53 + 33,称153是自幂数。 n为 1时,自幂数称为独身数。显然0,1,2,3,4,5,6,7,8,9都是自幂数。 n为 2时,没有自幂数。 n为 3时,自幂数称为水仙花数,有4个 n为 4时,自幂数称为四叶玫瑰数,共有3个 n为 5时,自幂数称为五角星数,共有3个 n为 6时,自幂数称为六合数, 只有1个 n为 7时,自幂数称为北斗七星数, 共有4个 n为 8时,自幂数称为八仙数, 共有3个 n为 9时,自幂数称为九九重阳数,共有4个 n为10时,自幂数称为十全十美数,只有1个 编程寻找并输出 n 位的自幂数,n 由用户输入,每行输出一个数字。

In [5]:
# 方法一
n = int(input())
for num in range(10**(n-1),10**n):  # 遍历所有n位数
   sumOfnum = 0
   for i in str(num):       # num转为字符串,对其中的数字进行遍历,i为字符串
      sumOfnum = sumOfnum + int(i) ** n      # i转整数,计算其n次方累加
   if sumOfnum == num:                       # 若累加和与num值相同,是素数
      print(num)                             # 输出找到的素数

程序中对 num 中每位上的数字的 n 次方求和使用了三条语句,判断是否相等一条语句,这四条语句可以用列表推导式简化为一条语句实现: if num == sum([int(i) n for i in str(num)]): 其中:列表推导式 [int(i) n for i in str(num)] 得到的是num中每位上的数字的 n 次方的列表,sum()函数可以对列表中可计算元素求和。 在寻找水仙花数时,每次循环都要计算数中每位上的数字的 n次方,当 n 较大时,这个计算量是相当大的。为了减少时间开销,可以计算 0-9 中每个数的 n 次方存放在一个列表中,需要时,用索引的方法从中取 n 次方的计算结果直接用于计算,可以减少很多次幂运算,这个方法相对于其他方法可以减少约 50% 的时间开销。

In [6]:
# 方法二
n = int(input())
ls = [x ** n for x in range(10)]        # 推导出0-9中每个数的n次方存于列表
for num in range(10 ** (n - 1),10 ** n):  # 遍历所有n位数
   if num == sum([ls[int(i)] for i in str(num)]):    
      print(num)         # 输出找到的素数

例如计算三位自幂数时,先用列表推导式得到一个包含0-9的3次方的一个列表[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]。再判断100-999范围内每个数是否为自幂数时,str(num)把数字转为字符串,根据这个字符串序列推导出一个新列表,新列表中的元素为字符串中字符对应的整数的n次方。例如判断371时,将其转为字串’371’, '3','7','1' 这3个元素分别对应于列表ls中的27、343和1,从而产生新的列表[27,343,1],再用sum()函数对其求和并比较是否等于371,如果相等,可判定该数为自幂数。

In [4]:
def isNarcissus(num):
    """接收一个n位正整数为参数,判定其各位上数字的n次方的和是否与该数相等,返回布尔值"""
    return num == sum([int(i) ** len(str(num)) for i in str(num)])

print(*[i for i in range(10, 100000) if isNarcissus(i)])
# 153 370 371 407 1634 8208 9474   

两次利用列表推导式用一条语句实现

In [3]:
print(*[num for num in range(10, 100000) if num == sum([int(i) ** len(str(num)) for i in str(num)])])

用一条语句输出素数:

In [ ]:
print(*[x for x in range(2, int(input())) if not [y for y in range(2, x) if x % y == 0]])

通过列表推导式可以创建一个列表。但是,创建一个包含很多个元素的列表,会占用很大的存储空间,如果仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。 所以,如果列表元素可以按照某种算法循环推算出来,那就不必创建完整的列表,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器(Generator)。生成器推导式的结果是一个生成器对象,不是列表也不是元组。 生成器对象可以用next()方法或 next()函数进行遍历,也可以将其作为迭代器对象使用。不管用哪种方法访问其中的元素,当所有元素访问结束以后,对象会变空。如果需要重新访问其中的元素,必须重新创建该生成器对象。 创建生成器有很多种方法,一个简单的方法是把一个列表推导式的[]改成(),就创建了一个生成器。

In [7]:
g = ( i ** 3 for i in range(11))
print(type(g))                   # <class 'generator'>,g的数据类型为生成器
print(g)  # g是生成器对象,<generator object <genexpr> at 0x00000202A663DC00>
print(list(g))# 转为列表可输出[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
print(list(g))                    # 生成器对象被遍历后会变成空 []
g = ( i ** 3 for i in range(11))  # 重新创建生成器对象
print(next(g))                    # 输出 0
print(g.__next__())               # 输出 1
print(next(g))                    # 输出 8
print(list(g))       # 转为列表可输出[ 27, 64, 125, 216, 343, 512, 729, 1000]

可以看出,g是一个生成器对象,也是一个可遍历对象,无法直接使用print函数打印出它的值,可以在循环中作为可遍历对象使用,也可以用list()或tuple()生成器把它转换成列表或元组显示出来。 生成器对于生成大量的可遍历数据非常有效,并且可以大大提高程序对于内存的使用效率。