我是 Python 的新手,但我想学习更多,我给自己的第一个迷你项目是创建一个代码,可以接收给定用户名的输入,然后输出小时数他们在某个项目上工作。我在周末收到我部门员工的 csv,在该 csv 中,我有他们正在进行的各种项目以及专用于该项目的时间。 csv 文件的问题是该用户有重复的项目,所以当我的 csv 输出时,我需要它只显示一个项目名称和与该项目相关的所有时间。我怎样才能让我的代码读取重复项并只计算重复项的小时数并只使用一个项目名称?
这是我到目前为止想出的代码:
import csv
with open('Report.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
firsts = []
lasts = []
projects = []
hours = []
for row in readCSV:
first = row[0]
last = row[1]
project = row[2]
hour = row[3]
firsts.append(first)
lasts.append(last)
projects.append(project)
hours.append(hour)
First_name = input("Please enter the first name: ")
First_1 = firsts.index(First_name)
Last_1 = lasts[First_1]
project_1 = projects[First_1]
hours_1 = hours[First_1]
print(First_1, Last_1, project_1, hours_1)
这是 csv 的示例
First Last Project Hours
David Ayers AD-0002 Training 24
Oriana Morfitt AD-0002 Training 24
David Ayers AD-0003 Personal Time 8
David Ayers AD-0004 Sick Time 0
Oriana Morfitt AD-0005 Vacation 40
Sujatha Kavuri Beeline Blank 29
Sujatha Kavuri Beeline Blank 16
Sujatha Kavuri OPS-0001 General Operational Support 6
Jeff Moore OPS-0001 General Operational Support 5
Sri Mantri SRV-0001 Service Requests for Base and Direct Services 4
Prasanth Musunuru SRV-0001 Service Requests for Base and Direct Services 11
Prasanth Musunuru SRV-0001 Service Requests for Base and Direct Services 10
Jeff Moore SRV-0006 Standards and Processes 5
Jeff Moore SRV-0006 Standards and Processes 3
Jeff Moore SRV-2503 Internet Access Infrastructure Maintenance & Support 12.5
Jeff Moore SRV-2503 Internet Access Infrastructure Maintenance & Support 7
Jeff Moore 0024495915 Work Instructions (infrastructure) - time tracking 1
Sri Mantri 0026184229 Margin Controlling Java Rewrite 4
Sujatha Kavuri 0029157489 SCRM Life Cycle Extension 3
Jeff Moore 0031369443 Shopcall Attachment Changes 1
Jeff Moore 0031500942 MP Strategy 2015 - Spot PO via EDI (time tracking only) - 0031500942 1
请您参考如下方法:
我敢打赌有更好的方法来处理 pandas,但这也行得通:
import csv
# I've used full name to avoid duplicate first names in report
full_name = input('Enter your full name: ')
with open('Report.csv') as csvfile:
hour_summation = {}
read_csv = csv.reader(csvfile, delimiter=',')
for row in read_csv:
if ' '.join((row[0], row[1])) == full_name.strip():
hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(row[3])
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
print(k + ': ' + str(v) + ' hours')
Sujatha Kavuri 的成绩
Enter your full name: Sujatha Kavuri
This is Sujatha Kavuri full hours report:
Beeline Blank: 45 hours
OPS-0001 General Operational Support: 6 hours
编辑 - 我只对文件的一半进行了采样,因此结果并不完整。
希望这会有所帮助。
