码迷,mamicode.com
首页 > 其他好文 > 详细

setdefault和defaultdict

时间:2016-08-05 06:39:38      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

setdefault和defaultdict

#setdefault
periodic_table = {Hydrogen: 1, Helium: 2}
carbon = periodic_table.setdefault(Carbon, 12)
print(carbon)
print(periodic_table)
helium = periodic_table.setdefault(Helium, 947)
print(helium)
print(periodic_table)

#defaultdict
print(int())
from collections import defaultdict
periodic_table2 = defaultdict(int)
periodic_table2[Hydrogen] = 1
print(periodic_table2[Lead])
print(periodic_table2)
def no_idea():
    return Hub?
bestiary = defaultdict(no_idea)
bestiary[A] = Abominable Snowman
print(bestiary[B])

输出

12
{Carbon: 12, Helium: 2, Hydrogen: 1}
2
{Carbon: 12, Helium: 2, Hydrogen: 1}
0
0
defaultdict(<class int>, {Lead: 0, Hydrogen: 1})
Hub?

pprint 

技术分享

itertools

import itertools

count = 0
for item in itertools.chain([1, 2, 3], [a, b]):
    count += 1
    print(count, count)
    print(item)

print(-------------)
count = 0
for item in itertools.cycle([1, 2]):
    count += 1
    print(count, count)
    if count < 5:
        print(item)
    else:
        break

print(-------------)
#累积的值,默认累积和
for item in itertools.accumulate([1, 2, 3, 4]):
    print(item)

print(-------------)
def multiply(a, b):
    return a * b

for item in itertools.accumulate([1, 2, 3, 4], multiply):
    print(item)

输出

count 1
1
count 2
2
count 3
3
count 4
a
count 5
b
-------------
count 1
1
count 2
2
count 3
1
count 4
2
count 5
-------------
1
3
6
10
-------------
1
2
6
24

 

setdefault和defaultdict

标签:

原文地址:http://www.cnblogs.com/jzm17173/p/5739800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!