gpt4 book ai didi

Python 文件 IO - 构建字典并寻找最大值

转载 作者:太空宇宙 更新时间:2023-11-04 00:51:12 25 4
gpt4 key购买 nike

问题是返回此文本文件中参与者人数最多的事件的名称:

#Beyond the Imposter Syndrome 
32 students
4 faculty
10 industries
#Diversifying Computing Panel
15 students
20 faculty
#Movie Night
52 students

所以我想我必须将它拆分成一个字典,其中键作为事件名称,值作为其他行开头的整数之和。我遇到了很多麻烦,我想我把它弄得太复杂了。

这是我目前所拥有的:

def most_attended(fname):
'''(str: filename, )'''
d = {}
f = open(fname)
lines = f.read().split(' \n')
print lines
indexes = []
count = 0
for i in range(len(lines)):
if lines[i].startswith('#'):
event = lines[i].strip('#').strip()
if event not in d:
d[event] = []
print d
indexes.append(i)
print indexes
if not lines[i].startswith('#') and indexes !=0:
num = lines[i].strip().split()[0]
print num
if num not in d[len(d)-1]:
d[len(d)-1] += [num]
print d

f.close()

最佳答案

import sys
from collections import defaultdict
from operator import itemgetter

def load_data(file_name):
events = defaultdict(int)
current_event = None
for line in open(file_name):
if line.startswith('#'):
current_event = line[1:].strip()
else:
participants_count = int(line.split()[0])
events[current_event] += participants_count
return events


if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage:\n\t{} <file>\n'.format(sys.argv[0]))
else:
events = load_data(sys.argv[1])
print('{}: {}'.format(*max(events.items(), key=itemgetter(1))))

关于Python 文件 IO - 构建字典并寻找最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com