标签:
#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?
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
标签:
原文地址:http://www.cnblogs.com/jzm17173/p/5739800.html