我必须使用Python来解决这个问题。给定具有此结构的文件salaries.csv
:
City,Job,Salary
Delhi,Doctors,500
Delhi,Lawyers,400
Delhi,Plumbers,100
London,Doctors,800
London,Lawyers,700
London,Plumbers,300
Tokyo,Doctors,900
Tokyo,Lawyers,800
Tokyo,Plumbers,400
Lawyers,Doctors,300
Lawyers,Lawyers,400
Lawyers,Plumbers,500
Hong Kong,Doctors,1800
Hong Kong,Lawyers,1100
Hong Kong,Plumbers,1000
Moscow,Doctors,300
Moscow,Lawyers,200
Moscow,Plumbers,100
Berlin,Doctors,800
Berlin,Plumbers,900
Paris,Doctors,900
Paris,Lawyers,800
Paris,Plumbers,500
Paris,Dog catchers,400
根据律师工资的降序排序CSV文件
输出应该是这样的:
Tokyo,800
London,700
Delhi,400
我使用以下代码。,
import csv
reader = csv.DictReader(open('salaries.csv','rb'))
rows = sorted(reader)
a={}
for i in xrange(len(rows)):
if rows[i].values()[2]=='Lawyers':
a[rows[i].values()[1]]=rows[i].values()[0]
t = [i for i in sorted(a, key=lambda key:a[key], reverse=True)]
p=a.values()
p.sort()
p.reverse()
for i in xrange(len(a)):
print t[i]+","+p[i]
但是,我收到以下错误:
NameError("global name 'a' is not defined",)
有人可以帮助我吗?
答案 0 :(得分:0)
import csv
with open('salaries.csv','rb') as fin:
reader = csv.reader(fin)
reader.next()
sorted_salary=sorted(reader, key=lambda t: int( t[2] ), reverse=True)
for row in sorted_salary:
if row[1] == 'Lawyers':
print '{0},{1}'.format(row[0], row[2])
答案 1 :(得分:-1)
你可以做得更简单:
with open("salaries.csv") as f:
dct = csv.DictReader(f)
out = [(d["City"], d["Salary"])
for d in dct if d["Job"] == "Lawyers"]
out.sort(key=lambda x: int(x[1]),reverse=True)
print(out)
[('Hong Kong', '1100'), ('Tokyo', '800'), ('Paris', '800'), ('London', '700'), ('Delhi', '400'), ('Lawyers', '400'), ('Moscow', '200')]
(d["City"], d["Salary"]) for d in dct if d["Job"] == "Lawyers"]
找到Lawyers
的所有行,然后我们从字典中提取城市和工资。
然后out.sort(key=lambda x: int(x[1]),reverse=True)
根据第二个元素Salary
的整数值对元组列表进行排序。