本文介绍了字典或列表的数组或....?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我无法弄清楚如何设置Python数据结构来读取数据 看起来像这样(虽然有点简化和做作) : 州 县 学校 课程 最多允许学生 目前在校注册学生 内布拉斯加州,Wabash,Newville,数学,20,0 内布拉斯加州,Wabash,Newville,健身房,400, 0 内布拉斯加州,Tingo,Newfille,健身房,400,0 俄亥俄州,Dinger,OldSchool,英语,10,0 在我读入的每一行中,我将创建一个哈希条目并增加 注册学生的数量。 我在Perl中使用数组编写了一个例程哈希表(但语法 是一个熊)允许我读取数据并使用那些哈希表的数组到哈希表数组几乎所有东西都是动态 分配。 我能够填写哈希表和确定是否有任何学校课程 (例如健身房)已经超过了最大学生人数,或者没有学生报名参加。 不,这不是教室项目。我真的需要这个来完成我的工作。 我正在将我的Perl程序转换为Python,这部分让我感到困惑。 我之所以这么说转换一个完美的工作程序是因为没有 其他人也知道Perl或Python(但我相信有人新的 会比Perl更快地学习Python)和Perl程序已成为巨大且不断增长。 解决方案 你描述的python版本: 类TooManyAttendants(例外):传递 class Attendence(object): def __init __(self,max): self.max = int(max) self.total = 0 def accrue(self,other): self.total + = int(other) if self.total self.max :提高TooManyAttendants def __str __(自我): 返回"%s /%s" %(self.max,self.total) __repr__ = __str__ data = {} for i,line in枚举(文件(input.txt)): 打印行, 州,县,学校,cls,max_students,登记=地图( lambda s:s.strip(), line.rstrip(" \\\)&。分裂(",") ) 尝试: data.setdefault( state,{})。setdefault( county ,{})。setdefault( cls,Attendence(max_students))。accrue(注册) 除了TooManyAttendants: print" Too排队%i的许多服务员%(i + 1) 打印报告(数据) 然后你可以访问 a = data [" Nebraska"] [" Wabash"] [" Newville"] [" Math"] 打印a.max,a.total 如果大写不一,你可能需要做一些像 data.setdefault( state.upper(),{})。setdefault( county.upper(),{})。setdefault( cls.upper(),Attendence(max_students))。accrue(注册) 以确保它们被归一化为相同的分组。 -tkc Tim Chase: 我不知道是否''一个很好的做法。 我建议将该部分解压缩一点,以便制作它多一点 可读。 再见, 。熊市场 > __repr__ = __str__ 我已经在几个地方看到了它,而且它非常清楚它正在做什么。 。 br> 我建议将该部分解压缩一点,以使其更加可靠。 我玩格式化并且我真的不喜欢 我想出的格式。我的其他可能的选择是: 尝试: 数据\ .setdefault(state,{})\ .setdefault(county,{})\ .setdefault(cls,Attendence(max_students))\ .accrue(已注册) 除了TooManyAttendants: 或 尝试: (数据 .setdefault(state,{}) .setdefault(county,{}) .setdefault(cls,Attendence(max,0)) ).accrue(已注册) 除了TooManyAttendants: 两者都强调了与他们的 参数,这可能会有所帮助。哪一个是更好的是个人偏好的问题: *没有额外的字符但很难阅读 *反斜杠,或 *一对额外的parens -tkcI can''t figure out how to set up a Python data structure to read in datathat looks something like this (albeit somewhat simplified and contrived):StatesCountiesSchoolsClassesMax Allowed StudentsCurrent enrolled StudentsNebraska, Wabash, Newville, Math, 20, 0Nebraska, Wabash, Newville, Gym, 400, 0Nebraska, Tingo, Newfille, Gym, 400, 0Ohio, Dinger, OldSchool, English, 10, 0With each line I read in, I would create a hash entry and increment thenumber of enrolled students.I wrote a routine in Perl using arrays of hash tables (but the syntaxwas a bear) that allowed me to read in the data and with those arrays ofhash tables to arrays of hash tables almost everything was dynamicallyassigned.I was able to fill in the hash tables and determine if any school class(e.g. Gym) had exceeded the number of max students or if no students hadenrolled.No, this is not a classroom project. I really need this for my job.I''m converting my Perl program to Python and this portion has me stumped.The reason why I''m converting a perfectly working program is because noone else knows Perl or Python either (but I believe that someone newwould learn Python quicker than Perl) and the Perl program has becomehuge and is continuously growing. 解决方案A python version of what you describe:class TooManyAttendants(Exception): passclass Attendence(object):def __init__(self, max):self.max = int(max)self.total = 0def accrue(self, other):self.total += int(other)if self.total self.max: raise TooManyAttendantsdef __str__(self):return "%s/%s" % (self.max, self.total)__repr__ = __str__data = {}for i, line in enumerate(file("input.txt")):print line,state, county, school, cls, max_students, enrolled = map(lambda s: s.strip(),line.rstrip("\r\n").split(","))try:data.setdefault(state, {}).setdefault(county, {}).setdefault(cls, Attendence(max_students)).accrue(enrolled)except TooManyAttendants:print "Too many Attendants in line %i" % (i + 1)print repr(data)You can then access things likea = data["Nebraska"]["Wabash"]["Newville"]["Math"]print a.max, a.totalIf capitalization varies, you may have to do something likedata.setdefault(state.upper(), {}).setdefault(county.upper(), {}).setdefault(cls.upper(), Attendence(max_students)).accrue(enrolled)to make sure they''re normalized into the same groupings.-tkcI don''t know if that''s a good practice.I suggest to decompress that part a little, to make it a little morereadable.Bye,bearophileI''ve seen it in a couple places, and it''s pretty explicit whatit''s doing.I suggest to decompress that part a little, to make it a little morereadable.I played around with the formatting and didn''t really like any ofthe formatting I came up with. My other possible alternatives were:try:data \.setdefault(state, {}) \.setdefault(county, {}) \.setdefault(cls, Attendence(max_students)) \.accrue(enrolled)except TooManyAttendants:ortry:(data.setdefault(state, {}).setdefault(county, {}).setdefault(cls, Attendence(max, 0))).accrue(enrolled)except TooManyAttendants:Both accentuate the setdefault() calls grouped with theirparameters, which can be helpful. Which one is "better" is amatter of personal preference:* no extra characters but hard to read* backslashes, or* an extra pair of parens-tkc 这篇关于字典或列表的数组或....?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-29 09:50