【python】collections

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
def csv_reader(fd, delimiter='\t'):
    def gen():
        for i in fd:
            yield i.rstrip('\n').split(delimiter)
    return gen()
    
def read_tsv(input_file, quotechar=None):
    with open(input_file, 'r', encoding='utf8') as f:
        reader = csv_reader(f)
        headers = next(reader) # 首行是header
        Example = namedtuple('Example', headers) 
        examples = []
        for line in reader:
            example = Example(*line)
            examples.append(example)
        return examples
        
print(read_tsv("file_name"))

输入

num	type
16111	definition
20381	digit-money

输出

[Example(num='16111', type='definition'), Example(num='20381', type='digit-money')]
上一篇:HashMap和TreeMap类


下一篇:Java 实例 - 数组获取最大和最小值