<span style="font-size:14px;"># -*- coding: utf-8 -*-
#函数进阶 lambda匿名函数 X:X+n :前为参数 后卫函数体
from math import pi
def make_incrementor(n):
return lambda x: x + n
#f是函数make_incrementor(42)的返回值 即f = lambda x: x + n
f = make_incrementor(42)
print f(1)
#结果为:43
print('-')*40
#队列
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # Terry arrives
queue.append("Graham") # Graham arrives
queue.popleft() # The first to arrive now leaves 第一个到达的现在离开
#’Eric’
queue.popleft() # The second to arrive now leaves 第二个到达的现在离开
#’John’
print queue # Remaining queue in order of arrival 按到达次序排列的剩余队列
#deque([’Michael’, ’Terry’, ’Graham’])
print('-')*40
#squares = map(lambda x : x ** 2, range(10))
squares = [x**2 for x in range(10)]
print squares
print('-')*40
#列表的综合应用
list1 = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
print list1
#等同于
combs = []
for x in[1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x,y))
print combs
print('-')*40
#结果:[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
vec = [-4, -2, 0, 2, 4]
print [x*2 for x in vec]
#结果:[-8, -4, 0, 4, 8]
print [x for x in vec if x >= 0]
#结果:[0, 2, 4]
print [abs(x) for x in vec]
#结果:[4, 2, 0, 2, 4]
print('-')*40
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
print [weapon.strip() for weapon in freshfruit]
#结果:['banana', 'loganberry', 'passion fruit']
print('-')*40
print [(x, x**2) for x in range(6)]
#结果:[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
print('-')*40
vec = [[1,2,3], [4,5,6], [7,8,9]]
print [num for elem in vec for num in elem]
#结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
print [str(round(pi, i)) for i in range(1, 6)]
#结果:['3.1', '3.14', '3.142', '3.1416', '3.14159']
</span>
Python列表操作(三)
最新推荐文章于 2021-12-20 09:44:49 发布