我有以下文本文件:
id gen age mar loc inc iscr escr
51 F 46 M 0 15100 531 555
52 M 29 M 2 14200 673 633
53 M 25 S 0 22200 742 998
54 M 36 M 2 1000 677 646
55 F 99 S 0 10600 608 998
56 F 45 M 2 6100 710 743
57 M 99 M 2 16500 679 646
58 F 37 M 0 7400 637 683
59 M 45 S 0 22800 683 998
60 M 22 S 0 6400 699 998
61 M 32 S 0 3100 721 998
现在,我想制作一个对第一行中的字段名称进行过滤的函数,例如,如果调用该函数:filter('inc')
您将在“ inc”上过滤此列表。有谁可以帮助您?
您还可以创建一个函数,该函数为您提供字典列表,其中包含文本文件数据中的每一行:
def get_data(filename):
data = []
with open(filename) as in_file:
headers = next(in_file).split()
for line in in_file:
row = dict(zip(headers, line.strip().split()))
data.append(row)
return data
它返回以下内容:
{'id': '51', 'gen': 'F', 'age': '46', 'mar': 'M', 'loc': '0', 'inc': '15100', 'iscr': '531', 'escr': '555'}
{'id': '52', 'gen': 'M', 'age': '29', 'mar': 'M', 'loc': '2', 'inc': '14200', 'iscr': '673', 'escr': '633'}
{'id': '53', 'gen': 'M', 'age': '25', 'mar': 'S', 'loc': '0', 'inc': '22200', 'iscr': '742', 'escr': '998'}
...
然后,您可以使用列表推导过滤出这些数据:
>>> data = get_data('filter.txt')
>>> [row['inc'] for row in data]
['15100', '14200', '22200', '1000', '10600', '6100', '16500', '7400', '22800', '6400', '3100']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句