- zip()
- itertools.zip_longest()
- %time
- for 循环单行输出
- list 技巧
- 迭代器
- 生成器
- map()
- zip()
from pathlib import Path
Path.glob:可以用来查询文件名
import csv
csv.reader:用来读取csv文件,每一行都是一个tuple
from collections import defaultdict
defaultdict(int):默认为0
defaultdict(list):默认为空表 []
# 通过字典来调用变量 aa = 'alex' bb = 'brandon' c = {'a':aa, 'b':bb} c['a'][:2]
# 通过 print 方式写入数据 # 直接遍历 open 后的文件读取每行信息 import csv for file in names_dir.glob('*.txt'): with open(file) as name_file, open(npg_males / file.name, 'w') as males_file, open(npg_females / file.name, 'w') as females_file: for line in name_file: name, gender, count = line.split(',') if gender == 'F': print(name, count, sep = ',', end = '', file = females_file) else: print(name, count, sep = ',', end = '', file = males_file)
zip 高阶应用
说明:将 a 排序,然后按照 a 的排序规则,将 b 中的所有元素进行相应排序
a = ['B', 'A'] b = [[1, 0], [0, 1], [1, 2]] print(list(list(zip(*sorted(zip(a, *b))))[0])) print(list(zip(*sorted(zip(a, *b))))[1:]) output: ['A', 'B'] [(0, 1), (1, 0), (2, 1)]
实现过程拆解如下:
a = ['B', 'A'] b = [[1, 0], [0, 1], [1, 2]] tmp = zip(a, *b) tmp_list = list(zip(*sorted(tmp))) print(list(tmp_list[0])) print(tmp_list[1:])