像sql一样在python中查询csv文件
这显然是一个流行的面试问题。
有 2 个包含恐龙数据的 CSV 文件。我们需要查询它们以返回满足特定条件的恐龙。
注意 - 我们不能使用额外的模块,如 q、fsql、csvkit 等。
file1.csv:
NAME,LEG_LENGTH,DIET
Hadrosaurus,1.2,herbivore
Struthiomimus,0.92,omnivore
Velociraptor,1.0,carnivore
Triceratops,0.87,herbivore
Euoplocephalus,1.6,herbivore
Stegosaurus,1.40,herbivore
Tyrannosaurus Rex,2.5,carnivore
file2.csv:
NAME,STRIDE_LENGTH,STANCE
Euoplocephalus,1.87,quadrupedal
Stegosaurus,1.90,quadrupedal
Tyrannosaurus Rex,5.76,bipedal
Hadrosaurus,1.4,bipedal
Deinonychus,1.21,bipedal
Struthiomimus,1.34,bipedal
Velociraptor,2.72,bipedal
使用论坛:速度 = ((STRIDE_LENGTH / LEG_LENGTH) - 1) * SQRT(LEG_LENGTH * g),其中 g = 9.8 m/s^2
编写一个程序来读取 csv 文件,并仅打印双足恐龙的名称,按速度从快到慢排序。
在 SQL 中,这很简单:
select f2.name from
file1 f1 join file2 f2 on f1.name = f2.name
where f1.stance = 'bipedal'
order by (f2.stride_length/f1.leg_length - 1)*pow(f1.leg_length*9.8,0.5) desc
如何在 python 中做到这一点?