关于python:Python-的高级用法

7次阅读

共计 1666 个字符,预计需要花费 5 分钟才能阅读完成。

创立字典

1. 创立空字典

>>> dic = {}
>>> type(dic)
<type 'dict'>

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)

正文完
 0