1.使用生成式(推导式)语法
···
prices = {
'AAPL': 191.88,
'GOOG': 1186.96,
'IBM': 149.24,
'ORCL': 48.44,
'ACN': 166.89,
'FB': 208.09,
'SYMC': 21.29
}
prices2 = {key: value for key, value in prices.items() if value > 100}
print(prices2)
···

类似于C# linq筛选
2.嵌套的列表
names = ['关羽', '张飞', '赵云', '马超', '黄忠']
courses = ['语文', '数学', '英语']
# 录入五个学生三门课程的成绩
# 错误 - 参考http://pythontutor.com/visualize.html#mode=edit
# scores = [[None] * len(courses)] * len(names)
scores = [[None] * len(courses) for _ in range(len(names))]
for row, name in enumerate(names):
for col, course in enumerate(courses):
scores[row][col] = float(input('请输入%s的%s成绩: '%(name,course)))
print(scores)

两个一维数组组成的二维数组
3.heapq用法
"""
从列表中找出最大的或最小的N个元素
堆结构(大根堆/小根堆)
"""
import heapq
list1 = [34, 25, 12, 99, 87, 63, 58, 78, 88, 92]
list2 = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
print(heapq.nlargest(3, list1))
print(heapq.nsmallest(3, list1))
print(heapq.nlargest(2, list2, key=lambda x: x['price']))
print(heapq.nlargest(2, list2, key=lambda x: x['shares']))

4.itertools
转自https://www.liaoxuefeng.com/wiki/897692888725344/983420006222912
4.1 cycle()
import itertools
cs = itertools.cycle('ABC') # 注意字符串也是序列的一种
for c in cs:
... print c
...
'A'
'B'
'C'
'A'
'B'
'C'
...
无限循环
4.2 repeat()
ns = itertools.repeat('A', 10)
for n in ns:
... print n
...
打印10次'A'
可无限U型循环一个元素,第二个参数限定次数
4.3 chain()
for c in itertools.chain('ABC', 'XYZ'):
print c
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'
将两个对象串联在一起
4.4 groupby()
for key, group in itertools.groupby('AAABBBCCAAA'):
... print key, list(group) # 为什么这里要用list()函数呢?
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
相邻的重复元素单独挑出来
4.5 组合
for c in itertools.combinations('ABCDE', 3):
print(c)

4.6笛卡尔积
for c in itertools.product('ABCD', '123'):
print(c)

4.7找出出现次数最多的元素
"""
找出序列中出现次数最多的元素
"""
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around',
'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes',
'look', 'into', 'my', 'eyes', "you're", 'under'
]
counter = Counter(words)
print(counter.most_common(3))

网友评论