【发布时间】:2021-04-09 22:51:43
【问题描述】:
美好的一天!
我正在尝试找到给定数据集的最小值和最大值
foo,1,1
foo,2,5
foo,3,0
bar,1,5
bar,2,0
bar,3,0
foo,1,1
foo,2,2
foo,3,4
bar,1,4
bar,2,0
bar,3,1
foo,1,4
foo,2,2
foo,3,3
bar,1,1
bar,2,3
bar,3,0
我尝试使用第 1 列和第 2 列作为 ID 和第 3 列作为值对我的数据进行排序
from collections import defaultdict
data = defaultdict(list)
with open("file1.txt", 'r') as infile:
for line in infile:
line = line.strip().split(',')
meta = line[0]
id_ = line[1]
value = line[2]
try:
value = int(line[2])
data[meta+id_].append(value)
except ValueError:
print ('nope', sep='')
我的函数的输出是:
defaultdict(list,
{'foo1': ['1', '1', '4'],
'foo2': ['5', '2', '2'],
'foo3': ['0', '4', '3'],
'bar1': ['5', '4', '1'],
'bar2': ['0', '0', '3'],
'bar3': ['0', '1', '0']})
请告知如何获取每个 ID 的最小值和最大值?
所以我需要这样的输出:
defaultdict(list,
{'foo1': ['1', '4'],
'foo2': ['2', '5'],
'foo3': ['0', '4'],
'bar1': ['1', '5'],
'bar2': ['0', '3'],
'bar3': ['0', '1']})
更新:
在@AndiFB 的帮助下,我将排序添加到我的列表中:
def sorting_func(string):
return int(string)
from collections import defaultdict
data = defaultdict(list)
with open("file1.txt", 'r') as infile:
for line in infile:
line = line.strip().split(',')
meta = line[0]
id_ = line[1]
value = line[2]
try:
if value != "-":
value = int(line[2])
data[meta+id_].append(value)
data[meta+id_].sort(key=sorting_func)
print("max:", *data[meta+id_][-1:], 'min:',*data[meta+id_][:1])
except ValueError:
print ('nope', sep='')
data
输出:
max: 1 min: 1
max: 5 min: 5
max: 0 min: 0
max: 5 min: 5
max: 0 min: 0
max: 0 min: 0
max: 1 min: 1
max: 5 min: 2
max: 4 min: 0
max: 5 min: 4
max: 0 min: 0
max: 1 min: 0
max: 4 min: 1
max: 5 min: 2
max: 4 min: 0
max: 5 min: 1
max: 3 min: 0
max: 1 min: 0
defaultdict(list,
{'foo1': [1, 1, 4],
'foo2': [2, 2, 5],
'foo3': [0, 3, 4],
'bar1': [1, 4, 5],
'bar2': [0, 0, 3],
'bar3': [0, 0, 1]})
请告知如何只保存列表中的最小值和最大值(第一个和最后一个)?
得到这样的东西:
defaultdict(list,
{'foo1': ['1', '4'],
'foo2': ['2', '5'],
'foo3': ['0', '4'],
'bar1': ['1', '5'],
'bar2': ['0', '3'],
'bar3': ['0', '1']})
【问题讨论】:
标签: python-3.x