4000-520-616
欢迎来到免疫在线!(蚂蚁淘生物旗下平台)  请登录 |  免费注册 |  询价篮
主营:原厂直采,平行进口,授权代理(蚂蚁淘为您服务)
咨询热线电话
4000-520-616
当前位置: 首页 > 新闻动态 >
热卖商品
新闻详情
Python:读取和分析CSV文件 - 问答 - Python中文网
来自 : www.cnpython.com/qa/681... 发布时间:2021-03-24
def isSubjectAward(subject, student): \'\'\' Test to see if this student has earned the honor role\'\'\' return Falsewith open(\'data.csv\') as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=\",\") for student in csv_reader: if isHonorRole(student): \'\'\' Add to the honor role \'\'\' for subject in subjects: if isSubjectAward(subject, student):

好吧,现在我们需要实现一个逻辑,来划分谁赢得了主题奖。在

def isSubjectAward(subject, student): \'\'\' Test to see if this student has earned the subject award\'\'\' grade = float(student[subject]) highest = roles[subject][\'highest grade\'] students = roles[subject][\'students\'] student = (student[\'First\'], student[\'Last\']) # is this grade higher than the current highest? if grade highest: # we have a new highest! # clear the list students = [] students.append(student) # set new highest highest = grade elif grade == highest: # add to list of students students.append(student) else: return # There where changes to the list roles[subject][\'highest grade\'] = grade roles[subject][\'students\'] = studentsprint json.dumps(roles, sort_keys=True, indent=4)

现在我们有了主题奖获奖者:

{ \"Art\": { \"highest grade\": 100.0,  \"students\": [ \"Nathan\",  \"Bryson\" \"Chase\",  \"Putnam\" \"English\": { \"highest grade\": 99.0,  \"students\": [ \"Josiah\",  \"Gower\" \"Geography\": { \"highest grade\": 100.0,  \"students\": [ \"Ismaila\",  \"LeBlanc\" \"Gym\": { \"highest grade\": 100.0,  \"students\": [ \"Woo Taek (James)\",  \"Irvine\" \"History\": { \"highest grade\": 100.0,  \"students\": [ \"Tami\",  \"Easterbrook\" \"Math\": { \"highest grade\": 99.0,  \"students\": [ \"Carson\",  \"Whicher\" \"Music\": { \"highest grade\": 100.0,  \"students\": [ \"Jamie\",  \"Bates\" \"Michael\",  \"Giroux\" \"Science\": { \"highest grade\": 100.0,  \"students\": [ \"Jonathan\",  \"Emes\" \"Jack\",  \"Hudspeth\" \"honor role\": []

找到学生的荣誉角色应该是微不足道的。尤其是如果我们有几个辅助函数:

def getOverallAverage(student): \'\'\' Returns the average of all the student\'s subject grades \'\'\' total = sum([float(student[subject]) for subject in subjects]) return total/len(subjects)def getName(student): \'\'\'Extracts the student\'s first and last name as a tuple\'\'\' return \' \'.join((student[\'First\'], student[\'Last\']))def isHonorRole(student): \'\'\' Test to see if this student has earned the honor role\'\'\' cutoff = 80 if getOverallAverage(student) = cutoff: roles[\'honor role\'].append(getName(student)) return False

荣誉角色是:

\"honor role\": [ \"Devin Agorhom\",  \"Jevon Ahn\",  \"Darion Ajagu\",  \"Chandler Akahira\",  \"Stas Al-Turki\",  \"Bryce Allison\",  \"Tucker Allison\",  \"Eric Andrews\",  \"Henry Angeletti\",  \"Harry Apps\",  \"Jesse Arnold\",  \"Benjamin Aucoin\",  \"Matthew Bainbridge\",  \"Geordie Ball\",  \"Sean Barbe\",  \"Dwayne Barida\",  \"Jamie Bates\",  \"Bradley Baverstock\",  \"Adam Beckman\",  \"Michael Becq\",  \"Joshua Berezny\",  \"Aaron Best\",  \"Doug Bolsonello\",  \"Richard Bolton\",  \"Trevor Bolton\",  \"Travis Bonellos\",  \"Daniel Boulet\",  \"Nicholas Bowman\",  \"Connor Brent\",  \"Michael Britnell\",  \"Shu Brooks\",  \"Cody Brown\",  \"Dylan Brown\",  \"Mark Brown\",  \"Xinkai (Kevin) Brown\",  \"Daniel Bryce\",  \"Nathan Bryson\",  \"Greg Bull\",  \"Eric Burnham\",  \"Kevin Burns\",  \"Rhys Caldwell\",  \"Evan Campbell\",  \"Jeremiah Carroll\",  \"Ian Cass\",  \"Robert Cassidy\",  \"Matt Catleugh\",  \"Garin Chalmers\",  \"Matthew Chan\",  \"Ryan Cheeseman\",  \"Jack Chen\",  \"Phillipe Chester\",  \"Cameron Choi\",  \"Jason Clare\",  \"Brandon Clarke\",  \"Justin Clarke\",  \"Reid Clarke\",  \"Brendan Cleland\",  \"Andrew Clemens\",  \"Matthew Clemens\",  \"Pete Conly\",  \"Marc Coombs\",  \"Leif Coughlin\",  \"Michael Cox\",  \"Michael Creighton\",  \"Raymond Croke\",  \"Andrew Cummins\",  \"William Cupillari\",  \"James Davidson\",  \"Maxim Davis\",  \"Peter Davis\",  \"Daniel Dearham\",  \"Michael Deaville\",  \"Andrew Decker\",  \"Alex Del Peral\",  \"Kobe Dick\",  \"Alec Dion\",  \"Gaelan Domej\",  \"Harrison Dudas\",  \"Ted Duncan\",  \"Andrew Dunkin\",  \"Micah Dupuy\",  \"Cameron Dziedzic\",  \"Tami Easterbrook\",  \"Ethan Ellis\",  \"Jonathan Emes\",  \"Kevin Ernst\",  \"Taylor Evans\",  \"Jack Everett\",  \"Andrew Fabbri\",  \"Les Fawns\",  \"Cameron Faya\",  \"Patrick Feaver\",  \"Josh Ferrando\",  \"Aidan Flett\",  \"Tommy Flowers\",  \"Gregory Friberg\",  \"Craig Friesen\",  \"Keegan Friesen\",  \"Ryan Fullerton\",  \"Jason Gainer\",  \"Adam Gall\",  \"Ryan Gallant\",  \"Michael Gasparotto\",  \"Scott Gerald\",  \"Michael Giroux\",  \"Ramanand Gleeson\",  \"Jack Goldblatt\",  \"Daniel Gonzalez-Stewart\",  \"Christopher Got\",  \"Josiah Gower\",  \"Zachary Grannum\",  \"Stuart Gray\",  \"Gonzalo Grift-White\",  \"Aris Grosvenor\",  \"Eric Hager\",  \"I\\u00c3\\u00b1igo Hamel\",  \"Davin Hamilton\",  \"Matthew Hanafy\",  \"Christopher Harpur\",  \"Tomas Hart\",  \"Gage Haslam\",  \"Ross Hayward\",  \"Sean Heath\",  \"Ryan Hess\",  \"Matthew Hessey\",  \"Stephen Hewis\",  \"Michael Hill\",  \"Edward Holbrook\",  \"Gavin Holenski\",  \"Brendan Holmes\",  \"Gregory Houston\",  \"Douglas Howarth\",  \"Conor Hoyle\",  \"Agustin Huang\",  \"Jack Hudspeth\",  \"James Humfries\",  \"David Hunchak\",  \"Jesse Im\",  \"Steve Inglis\",  \"Woo Taek (James) Irvine\",  \"Kenny James\",  \"Eric Jang\",  \"Erik Jeong\",  \"Michael Jervis\",  \"Brett Johnson\",  \"Adam Johnston\",  \"Ben Johnstone\",  \"Taylor Jones\",  \"Braedon Journeay\",  \"Neil Karakatsanis\",  \"David Karrys\",  \"Ryan Keane\",  \"Josh Kear\",  \"Alexander Kee\",  \"Joshua Khan\",  \"Matthew Kim\",  \"David Kimbell Boddy\",  \"Daniel King\",  \"Tristan Knappett\",  \"Timothy Koornneef\",  \"Michael Krikorian\",  \"George Kronberg\",  \"Danny Kwiatkowski\",  \"Chris Lackey\",  \"Spenser LaMarre\",  \"Matthew Lampi\",  \"Craig Landerville\",  \"Dallas Lane\",  \"Matthew Lanselle\",  \"Allen Lapko\",  \"Cory Latimer\",  \"Ben Lawrence\",  \"Matthew Lebel\",  \"Ismaila LeBlanc\",  \"Christopher Lee\",  \"Bailey Legiehn\",  \"Andy Lennox\",  \"Samuel Leonard\",  \"Sam Lockner\",  \"Jeffrey MacPherson\",  \"Simon Mahoney\",  \"Lucas Maier\",  \"Trent Manley\",  \"Jeremy Manoukas\",  \"Nathanial Marsh\",  \"Alastair Marshall\",  \"Connor Mattucci\",  \"Samuel McCormick\",  \"Cameron McCuaig\",  \"Ronan Mcewan\",  \"John McGuire\",  \"Brian McNaughton\",  \"Christopher McPherson\",  \"Alistair McRae\",  \"Andrew Medlock\",  \"Trevor Meipoom\",  \"Justin Metcalfe\",  \"Chieh (Jack) Miller\",  \"Graham Miller\",  \"Josh Miller\",  \"Salvador Miller\",  \"Max Missiuna\",  \"Jack Mitchell\",  \"Michael Morris\",  \"Paul Morrison\",  \"Morgan Moszczynski\",  \"Curtis Muir\",  \"Christopher Murphy\",  \"Mark Murphy\",  \"Hiroki Nakajima\",  \"Michael Neary\",  \"James Nelson\",  \"John Nicholson\",  \"Stephen Nishida\",  \"Michael Nowlan\",  \"Jason O\'Brien\",  \"Manny O\'Brien\",  \"James O\'Donnell\",  \"Spencer Olubala Paynter\",  \"Daniel Ortiz\",  \"Jihwan Ottenhof\",  \"Joel Ottenhof\",  \"Roger Owen\",  \"Jason Ozark\",  \"Brent Pardhan\",  \"Bernard Park\",  \"Jason Parker\",  \"Alistair Pasechnyk\",  \"James Patrick\",  \"Hunter Pellow\",  \"Jason Pennings\",  \"Brant Perras\",  \"Michael Petersen\",  \"Jordan Petrov\",  \"Don Philp\",  \"Adam Piil\",  \"Ryan Pirhonen\",  \"Alex Pollard\",  \"Daniel Postlethwaite\",  \"John-Michael Potter\",  \"Tim Powell\",  \"Chad Power\",  \"Jack Pratt\",  \"Alexander Price\",  \"Tyler Purdie\",  \"Andrew Purvis\",  \"Colin Purvis\",  \"Chase Putnam\",  \"Kael Radonicich\",  \"Curtis Ravensdale\",  \"Brett Ray\",  \"Forrest Reid\",  \"Aiden Ren\",  \"Tyler Rennicks\",  \"Alden Revell\",  \"Joshua Robinson\",  \"Richard Roffey\",  \"Michael Rose\",  \"Nicholas Roy\",  \"Christopher Samuel\",  \"Chris Sandilands\",  \"Christopher Sarbutt\",  \"David Saun\",  \"David Scharman\",  \"Adam Schoenmaker\",  \"Derek Schultz\",  \"Rocky Scuralli\",  \"Turner Seale\",  \"Bryan Senn\",  \"Alexander Serena\",  \"Seth Shaubel\",  \"Alex Shaw\",  \"Denroy Shaw\",  \"William Sibbald\",  \"Curtis Simao\",  \"Greg Simm\",  \"Nicholas Simon\",  \"Stuart Simons\",  \"Michael Skarsten\",  \"Matthew Skorbinski\",  \"Greg Slogan\",  \"Lucas Smith\",  \"Andrew South\",  \"Benjamin Sprowl\",  \"Jackson Staley\",  \"Reid Stencill-Hohn\",  \"Matthew Stevens\",  \"Jason Sula\",  \"Edward Sunderland\",  \"James Suppa\",  \"Jason Talbot\",  \"Tony Tan\",  \"Stuart Tang\",  \"Alex Temple\",  \"Leonard Theaker\",  \"Parker Thomas\",  \"Matthew Tisi\",  \"Scott Toda\",  \"Michael Toth\",  \"Zachary Trotter\",  \"Matthew Underwood\",  \"David Ure\",  \"Michael Utts\",  \"Joey Van Dyk\",  \"Jonathan Van Gaal\",  \"Chris Vandervies\",  \"Ryan Vickery\",  \"Dustin Wain\",  \"Brian Walker\",  \"Young-Jun Walsh\",  \"Brad Walton\",  \"Zachary Waugh\",  \"Matthew Webster\",  \"Samuel Welsh\",  \"Coleman West\",  \"Alexander Westendorp\",  \"Carson Whicher\",  \"David Whitney\",  \"Samuel Wilkinson\",  \"Kevin Williams\",  \"Aedan Williamson\",  \"Jason Wilson\",  \"William Wilson\",  \"David Wilton\",  \"Isaac Windeler\",  \"Liam Winter\",  \"Timothy Wong\",  \"Vladimir Wong\",  \"Robert Workman\",  \"Brian Yang\",  \"Owen Yates\",  \"Devin Young\",  \"Paul Young\",  \"Joshua Zhao\"

完成

网友2楼 ·

我的两分钱:

在一个循环中执行两个计算。尽管使用max和lambda看起来很酷而且可读性很强,而且仍然是O(n),但它也比下一个实现慢9倍,后者同时使用一个循环进行两个计算(Honour Roll和Subject Awards):

#!/usr/bin/env pythonimport csvwith open(\'/Users/edil3508/Downloads/honours.csv\') as csv_file: csv_reader = csv.reader(csv_file, delimiter=\",\") next(csv_reader, None) # skip the headers subjects = [\'English\', \'Math\', \'Geography\', \'Science\', \'Gym\', \'History\', \'Art\', \'Music\'] award_winners = [[\'\', 0], [\'\', 0], [\'\', 0], [\'\', 0], [\'\', 0], [\'\', 0], [\'\', 0], [\'\', 0]] # Honour Roll print(\'The honour roll students are:\') print(\"-\" * 80) for row in csv_reader: subtotal = 0 for i in range(2, 8 + 2): subtotal += int(row[i]) if int(row[i]) award_winners[i-2][1]: award_winners[i - 2][0] = row[1] + \" \" + row[0] award_winners[i - 2][1] = int(row[i]) avg = subtotal / 8 if avg 80: print(row[1] + \" \" + row[0], avg) # Subject Awards print(\"-\" * 80) print(\'The subject award winners are:\') print(\"-\" * 80) for ix, student_grade in enumerate(award_winners): print(\'{}: {} with {}\'.format(subjects[ix], student_grade[0], student_grade[1]))

输出:

^{pr2}$ 网友3楼 ·

[编辑]在与@edilio的合作下,我制作了一个更高效的版本,可以跟踪联系情况。其中有很多,所以这是一个相当重要的区别。代码很长,所以我将把它放在一个要点上。在

https://gist.github.com/SamyBencherif/fde7c3bca702545dd22739dd8caf796a

不需要for循环。事实上,你的第二个for循环中的语法完全是拙劣的。在

import csvwith open(\'C:/Users/rohan/Desktop/Google Drive/honourCSVreader/honour.csv\') as csv_file: csv_list = list(csv.reader(csv_file, delimiter=\",\"))[1:] # Subject Awards print(\'The subject award winners are:\') print(\'English\', max(csv_list, key=lambda row: row[2])) print(\'Math\', max(csv_list, key=lambda row: row[3])) print(\'Geography\', max(csv_list, key=lambda row: row[4])) 

等等

相关问题

本文链接: http://csvsouth.immuno-online.com/view-694751.html

发布于 : 2021-03-24 阅读(0)
公司介绍
品牌分类
联络我们
服务热线:4000-520-616
(限工作日9:00-18:00)
QQ :1570468124
手机:18915418616
官网:http://