Python列表操作(三)

<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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值