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
deque
#deque是一种双端队列,同时具有栈和队列的特征
def palindrome(word):
from collections import deque
dq = deque(word)
while len(dq) > 1:
if dq.popleft() != dq.pop():
return False
return True
palindrome('racecar')
OrderedDict
Counter计数