Python 的高级用法

创建字典

1.创建空字典

>>> dic = {}
>>> type(dic)

2.直接赋值创建

>>> dic = {'spam':1, 'egg':2, 'bar':3}
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}

3.通过关键字dict和关键字参数创建

>>> dic = dict(spam = 1, egg = 2, bar =3)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}

4.通过二元组列表创建

list = [('spam', 1), ('egg', 2), ('bar', 3)]
>>> dic = dict(list)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}

5.dict和zip结合创建

>>> dic = dict(zip('abc', [1, 2, 3]))
>>> dic
{'a': 1, 'c': 3, 'b': 2}

6.通过字典推导式创建

>>> dic = {i:2*i for i in range(3)}
>>> dic
{0: 0, 1: 2, 2: 4}

7.通过dict.fromkeys()创建

通常用来初始化字典, 设置value的默认值

>>> dic = dict.fromkeys(range(3), 'x')
>>> dic
{0: 'x', 1: 'x', 2: 'x'}

8.其他

>>> list = ['x', 1, 'y', 2, 'z', 3]
>>> dic = dict(zip(list[::2], list[1::2]))
>>> dic
{'y': 2, 'x': 1, 'z': 3}

排序字典

names = ['Alice', 'Tom', 'Harry', 'Jerry', 'Mike'] 
scores = [[8, 6, 7 ], [6, 7, 5], [8, 6, 9], [5, 7, 4], [8, 10, 9]]
dic = {}
len1  =len(names)
for i in range(len1):
    dic[names[i]]=sum(scores[i])
# dic1 = dict(zip(names, scores))
print(dic)
# print(dic1)
dic = dict(sorted(dic.items(), key=lambda x: x[1], reverse=True))
print(dic)

高阶函数

# for
l = []
for i in range(0, 11, 2):
    l.append(i*i)
print(l)

# filter
l1 = list(filter(lambda x: x%2==0 and pow(x, 1/2) in range(11), range(101)))
print(l1)

# map
l2 = list(map(lambda x: x*x, range(0, 11, 2)))
print(l2)

# List derivation
l3 = [i*i for i in range(0, 11, 2)]
print(l3)
# [0, 4, 16, 36, 64, 100]
# [0, 4, 16, 36, 64, 100]
# [0, 4, 16, 36, 64, 100]
# [0, 4, 16, 36, 64, 100]

一个奇怪的现象(生成二位数组) 

m = n = 3
test = [[0] * m] * n
print("test =", test)
输出结果如下:

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

是不是看起来没有一点问题?
一开始我也是这么觉得的,以为是我其他地方用错了什么函数,结果这么一试:

m = n = 3
test = [[0] * m] * n
print("test =", test)

test[0][0] = 233
print("test =", test)

输出结果如下:

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
test = [[233, 0, 0], [233, 0, 0], [233, 0, 0]]

也就是说matrix = [array] * 3操作中,只是创建3个指向array的引用,所以一旦array改变,matrix中3个list也会随之改变。 

生成二维数组利用列表生成式

from random import randint
l = [[randint(0, 11) for i in range(5)] for j in range(5)]
print(l)

你可能感兴趣的:(python高阶函数)