一、for遍历
1.dict items
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
gallahad the pure
robin the brave
2.enumerate
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
0 tic
1 tac
2 toe
3.同时遍历两个或更多的序列,可以使用 zip() 组合
如果想把两个或多个列表压缩在一起,可以使用 zip 把多个列表转换为一个对应元素的元组的单个列表中 如果列表的长度各异, zip 会在第一个列表结束时停止
data1 = [1,2,3,4,5]
data2 = [2,2,2,2,2]
# zip函数获得迭代器,只能遍历一次
# 1. 将多个列表压缩到一起, [(1, 2), (2, 2), (3, 2), (4, 2), (5, 2)]
dd = zip(data1, data2);
data = list(dd)
print(data)
# 2. 进行拆分, *号表示对参数进行拆分
a, b = zip(*data)
print(a, b)# (1, 2, 3, 4, 5) (2, 2, 2, 2, 2)
4.列表生成式 使用for或while进行数据结构的转换、迭代、遍历、计算等
arr = [9,1,3,5,2]
map = {
i : arr[i] * i
for i in range(0, len(arr))
}
print(map) # {0: 0, 1: 1, 2: 6, 3: 15, 4: 8}
二、排序(高阶函数)
使用内置函数sorted,对复杂结构进行排序
map = {0: 0, 1: 1, 2: 6, 3: 15, 4: 8}
map = sorted(map.items(), # 要排序的集合
key = lambda data : data[1],# 指定要排序的key
reverse = True) # True降序排序
print(map) # [(3, 15), (4, 8), (2, 6), (1, 1), (0, 0)]
#三、集合操作
1.defaultdict
创建一个可以在添加key的时候,自动初始化value的dictionary
from collections import defaultdict
dir = defaultdict(int)# int
dir['key1']
print(dir)
dir = defaultdict(list) # 列表
dir['key1'].append("value1")
dir['key1'].append("value2")
print(dir)
dir = defaultdict(dict) # 字典
dir['key1']['key1_1'] = 11
print(dir)
dir = defaultdict(float) #小数
dir['key1']
print(dir)
dir = defaultdict(str)# 字符串
dir['key1']
print(dir)
dir = defaultdict(bool)# 布尔
dir['key1']
print(dir)
dir = defaultdict(lambda:[0, 0, 0])# 自定义初始化的值
dir['key1']
print(dir)
2.Counter 统计元素出现的个数,可以用来绘制直方图
from collections import Counter
data = {'k1': 1, 'k2': 1, 'k3': 1, 'k4': 2, 'k5': 2 }
c = Counter([ kv[1] for kv in data.items() ])
# 全部的统计结果
print(c)# Counter({1: 3, 2: 2})
# 数量最大的一个
print(c.most_common(1))
#四、高阶函数 *agrs **kwargs
def func (*args, **kwargs) :
print("未命名:args=", args)
print("已命名:kwargs=", kwargs)
func(1,2, key=1)
输出结果
未命名:args= (1, 2)
已命名:kwargs= {'key': 1}
输入函数
def func2 (*args, **kwargs) :
key = 'f1'# 输入一个函数
f1 = kwargs.get(key)
return f1(args[0])
# 定义一个求和函数
def demo(args):
return sum(args)
data = [1, 2, 3, 4]
print(demo(data))
print(func2(data, f1=demo))
五、 help()函数
python默认有help(),可以查看,包、模块、函数、类、方法以及参数等的文档。 比如:
print(help(len))
返回以下结果
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
None
文章信息
- 本文作者:zhangxue
- 本文链接:https://lucksnow1989.github.io/article/13.脚本语言/python/基本语法/18高级语法糖.html
- 版权声明:本文为本人原创文章,遵循 CC 4.0 BY-NC-SA版权协议,转载请附上原文出处链接和本声明。