python list解析, map,生成器表达式

时间:2022-01-05 18:45:27

http://blog.csdn.net/mathboylinlin/article/details/9413551

  1. 列表解析:
books=[
        {"name":u"C#从入门到精通","price":23.7,"store":u"卓越"},
        {"name":u"ASP.NET高级编程","price":44.5,"store":u"卓越"},
        {"name":u"Python核心编程","price":24.7,"store":u"当当"},
        {"name":u"JavaScript大全","price":45.7,"store":u"当当"},
        {"name":u"Django简明教程","price":26.7,"store":u"新华书店"},
        {"name":u"深入Python","price":55.7,"store":u"新华书店"},
      ]
print [item[test] for item in books for test in item if item['name'].find('Python') >= 0 ]

输出结果:
[24.7, u’Python\u6838\u5fc3\u7f16\u7a0b’, u’\u5f53\u5f53’, 55.7, u’\u6df1\u5165Python’, u’\u65b0\u534e\u4e66\u5e97’]

  1. Map
def inc(x):
    return x+10

L = [1,2,3,4]
print map(inc,L)

print map((lambda x: x+10),L)

def add(x,y):
    return x+y

list1 = [11,22,33]
list2 = [44,55,66]
print map(add,list1,list2)

输出:
[11, 12, 13, 14]
[11, 12, 13, 14]
[55, 77, 99]

  1. 传参
def server(x=[]):
    x.append(1)
    print x

server([2])
server([2])
server([2])


server()
server()
server()

输出结果:
[2, 1]
[2, 1]
[2, 1]
[1]
[1, 1]
[1, 1, 1]

  1. 生成器表达式:
for n in (x + 1 for x in range(5)):
    print n,

输出结果:
1 2 3 4 5

def g(n):
    for i in range(n):
        yield i * 3
for i in g(9):
    print i,

输出结果:
1 2 3 4 5 0 3 6 9 12 15 18 21 24