Python 模块collections

1、深入理解python中的tuple的功能

基本特性

# 可迭代
name_tuple = ('0bug', '1bug', '2bug')
for name in name_tuple:
    print(name)
    
# 不可变
name_tuple = ('0bug', '1bug', '2bug')
name_tuple[0] = 'bug'  # TypeError: 'tuple' object does not support item assignment

# 不可变不是绝对的
change_tuple = (1, 2, [3, 4])
change_tuple[2][1] = 5
print(change_tuple)  # (1, 2, [3, 5])

# 拆包
lcg_tuple = ('0bug', '25', '175')
name, age, height = lcg_tuple
print(name, age, height)

lcg_tuple = ('0bug', '25', '175')
name, *other = lcg_tuple
print(other)  # ['25', '175']

tuple比list好的地方在哪?

1,性能优化

2.线程安全

3.可以作为dict的key

# 元祖对象是可哈希的,可作为字典的key
my_tuple = ('0bug','1bug')
dic = {}
dic[my_tuple] = 'name'
print(dic)  # {('0bug', '1bug'): 'name'}

4.拆包特性

如果拿c语言来类比,Tuple对应的是struct,而List对应的是array

2、namedtuple的功能详解

3、defaultdict的功能详解

4、deque的功能详解

5、Counter功能详解

6、OrderedDict功能详解

7、ChainMap功能详解

猜你喜欢

转载自www.cnblogs.com/0bug/p/8961376.html