Python的递推式构造列表(List comprehension)

介绍


我们在上一章学习了“Lambda 操作, Filter, Reduce 和 Map”, 但相对于map, filter, reduce 和lamdba, Guido van Rossum更喜欢用递推式构造列表(List comprehension)。在这一章我们将会涵盖递推式构造列表(List comprehension)的基础功能。

递推式构造列表(List comprehension)是在Python 2.0中添加进来的。本质上,它是一种数学家用来实现众所周知标记集合的Python方式。

在数学上,自然数的平方数是:{ x2 | x ∈ ℕ } 或者复数:{ (x,y) | x ∈ ℤ ∧ y ∈ ℤ }. 

在Python里,递推式构造列表(List comprehension)是一种定义和创建列表的优雅方式,这些列表通常是有一些约束的集合,并不是所有案例的集合。

对于函数map(), filter(), 和reduce(),递推式构造列表(List comprehension)是一个完整的lambda替代者。对于大部分人们,递推式构造列表(List comprehension)的语法更容易被人们掌握。 

举列


 在lamdba和map()这一章里,我们曾经设计了map()函数去把摄氏度的值转化为华氏度的值及其反函数。用递推式构造列表(List comprehension),可以这样表示:

>>> Celsius = [39.2, 36.5, 37.3, 37.8]
>>> Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ]
>>> print Fahrenheit
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999]
>>> 

下面的递推式构造列表(list comprehension)创建了毕达哥拉斯三元组:

>>> [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]
>>> 

两个集合的交叉乘积:

>>> colours = [ "red", "green", "yellow", "blue" ]
>>> things = [ "house", "car", "tree" ]
>>> coloured_things = [ (x,y) for x in colours for y in things ]
>>> print coloured_things
[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('green', 'house'), ('green', 'car'), ('green', 'tree'), ('yellow', 'house'), ('yellow', 'car'), ('yellow', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree')]
>>> 

(一)使用List Comprehension的好处 

 在了解Python的List Comprehension之前,我们习惯使用for循环创建列表,比如下面的例子:

numbers = range(10)

my_list = []
for number in numbers:
    my_list.append(number * number)
print(my_list)

可是在Python中,我们有更简洁,可读性更好的方式创建列表,就是List Comprehension:

my_list = [number * number for number in numbers]

我们也可以用map加上lambda实现上述List Comprehension的功能:

my_list = map(lambda a: a*a, numbers)

上面三个代码段的功能类似,除了map函数返回的是iterator,但是从可读性来说,List Comprehension是最好的

(二)一些较为复杂的List Comprehension

(1)加上if判断条件的List Comprehension:

my_list = [number for number in numbers if number % 2 == 0]

(2)多个维度,可以包含多个for

colors = ['Black', 'White']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for color in colors for size in sizes]

(三)Dictionary/Set Comprehension

与List Comprehension类似,我们可以对Dictionary和Set操作:

假设我们有如下两个列表:

names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']

我们利用内置函数zip将上面两个列表打包成包含元组的iterator zip(names, heros) ,用for循环输出如下:

('Bruce', 'Batman')
('Clark', 'Superman')
('Peter', 'Spiderman')
('Logan', 'Wolverine')
('Wade', 'Deadpool')

如果使用for循环把上面的iterator生成字典的话,代码如下:

my_dict = []
for name, hero in zip(names, heros):
    my_dict[name] = hero
print(my_dict)

而用Dictionary Comprehension的等价代码是这样的:

my_dict = {name: hero for name, hero in zip(names, heros)}
print(my_dict)

是不是更为简洁?同样也有Set Comprehension:

numbers = [1, 1, 2, 2, 2, 3, 4, 5]
my_set = {number for number in numbers}
print(my_set)

(四)Generator Comprehension

 生成器表达式与列表或其他序列类型相比,更节省内存,因为它一次只产出一个值,与List Comprehension的语法非常类似,只是不用[],而使用(),

比如我们求字母序列的ASCII码:

letters = 'ABCDEFG'
genexp_1etters = (ord(letter) for letter in letters)
for letter in genexp_1etters:
    print(letter)

程序输出ABCDEF的ASCII码 65 - 71.

 

递推式构造生成器(Generator Comprehension)


 递推式构造生成器(generator comprehension)在Python2.6中被介绍过。它们是一个简单的用圆括号括起来的生成表达式,除此之外,它的语法和工作原来都很像递推式构造列表(List comprehension),但是递推式构造生成器(generator comprehension)返回的是一个生成器而不是一个列表

>>> x = (x **2 for x in range(20))
>>> print(x)
 at 0xb7307aa4>
>>> x = list(x)
>>> print(x)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]

一些更高级的例子


 利用埃拉托斯特尼筛法(Sieve of Eratosthenes)计算1到100的质数:

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 100, i)]
>>> primes = [x for x in range(2, 100) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> 

我们把前面的例子写成更通俗的格式,所以我们可以计算到任意数n的质数的列表:

>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = [j for i in range(2,sqrt_n) for j in range(i*2, n, i)]

 如果我们去看no_primes的内容,就会发现一个问题。这里有很多重复的元素在这个列表里:

>>> no_primes
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99]
>>>

 这个无法容忍的问题将会在递推式构造集合(set comprehension)中被解决,我们将会在下一节中讲解

递推式构造集合(set comprehension)


递推式构造集合(set comprehension)与递推式构造列表(list comprehension)是很相似的,但是返回的是一个集合而不是列表。语法上,我们将采用花括号代替方括号去创建一个集合。递推式构造集合(set comprehension)是解决前一节中问题的正确方法。我们可以创建一个没有重复元素的非质数集合:

>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = {j for i in range(2,sqrt_n) for j in range(i*2, n, i)}
>>> no_primes
{4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99}
>>> primes = {i for i in range(n) if i not in no_primes}
>>> print(primes)
{0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
>>> 

利用递归函数来计算质数


 下面的Python脚本使用递归函数来创建质数,他的功能完全可以去检查一个到n的平方根的多个质数:

from math import sqrt
def primes(n):
    if n == 0:
        return []
    elif n == 1:
        return [1]
    else:
        p = primes(int(sqrt(n)))
        no_p = {j for i in p for j in range(i*2, n, i)}
        p = {x for x in range(2, n) if x not in no_p}
    return p

print(primes(40))
发布了104 篇原创文章 · 获赞 319 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/ljyljyok/article/details/104573348