collections 助力你的代码更加简洁、高效 & 优雅
from collections import Counter
lst = [1, 2, 3, 3, 2, 1, 1, 1, 2, 2, 3, 1, 2, 1, 1]
counter = Counter(lst)
Counter({1: 7, 2: 5, 3: 3})
lst = [1, 2, 3, 3, 2, 1, 1, 1, 2, 2, 3, 1, 2, 1, 1]
counter = Counter(lst)
print(counter[1])
lst = [1, 2, 3, 3, 2, 1, 1, 1, 2, 2, 3, 1, 2, 1, 1]
counter = Counter(lst)
print(counter.most_common(2))
[(1, 7), (2, 5)]
from collections import defaultdict
names_dict = defaultdict(int)
names_dict["Bob"] = 1
names_dict["Katie"] = 2
sara_number = names_dict["Sara"]
print(names_dict)
defaultdict(<classint >, { Bob : 1, Katie : 2, Sara : 0})
defaultdict(<classint >, { Bob : 1, Katie : 2, Sara : []})
from collections import deque
my_queue = deque(maxlen=10)
for i in range(10):
my_queue.append(i+1)
print(my_queue)
deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxlen=10)
for i in range(10, 15):
my_queue.append(i+1)
print(my_queue)
deque([6, 7, 8, 9, 10, 11, 12, 13, 14, 15], maxlen=10)
from collections import namedtuple
Person = namedtuple( Person , name age job )
Once the template is created, you can use it to create namedtuple objects. Let’s create 2 namedtuple’s for2 Persons andprint out their representation.
Person = namedtuple( Person , name age job )
Mike = Person(name= Mike , age=30, job= Data Scientist )
Kate = Person(name="Kate", age=28, job= Project Manager )
print(Mike)
print(Kate)
Person(name= Mike , age=30, job= Data Scientist )
Person(name= Kate , age=28, job= Project Manager )
关键词
元素
代码
方法
迭代器
数据类型
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。