defaultdict
相比于dict,如果key不存在,则会自动创建
from collections import defaultdict
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
list(d.items())
namedtuple
from collections import namedtuple
lis=["hello\t1","world\t2","china\t3"]
it=iter(lis)
headers = "name\tnum"
Example = namedtuple('Example', headers)
for x in it:
print(*x) # 按字符一个一个来读取的
example = Example(*x.strip().split("\t"))
print(example)
输出
h e l l o 1
Example(name='hello', num='1')
w o r l d 2
Example(name='world', num='2')
c h i n a 3
Example(name='china', num='3')