gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
Python collection库有什么作用?举例说明
- User
Python collection库有什么作用?举例说明
- Assistant
Python collection库提供了许多数据类型,包括但不限于以下:
- Counter:用于计算可哈希对象的数量,常用于统计文本中字母出现次数等。例如:
pythonfrom collections import Counter text = "hello world" counter = Counter(text) print(counter) # 输出结果为 # Counter({'l': 3, 'o': 2, 'e': 1, 'h': 1, 'w': 1, 'r': 1, 'd': 1, ' ': 1})- defaultdict:当字典的key不存在时,返回一个默认值。例如:
pythonfrom collections import defaultdict numbers = [1, 2, 3, 4, 2, 1, 3, 5, 6, 9] d = defaultdict(int) for number in numbers: d[number] += 1 print(d[10]) # 输出结果为 0,因为10没有出现过- deque:双端队列,可以快速在两端添加或删除元素。例如:
python