2

我得到了奇怪的结果,我终于注意到我在元组中放置空格的习惯导致了这个问题。如果你能重现这个问题并告诉我为什么它会这样工作,你就会节省我剩下的头发。谢谢!

jcomeau@intrepid:/tmp$ cat haversine.py
#!/usr/bin/python
def dms_to_float(degrees):
 d, m, s, compass = degrees
 d, m, s = int(d), float(m), float(s)
 float_degrees = d + (m / 60) + (s / 3600)
 float_degrees *= [1, -1][compass in ['S', 'W', 'Sw']]
 return float_degrees

jcomeau@intrepid:/tmp$ python
Python 2.6.7 (r267:88850, Jun 13 2011, 22:03:32) 
[GCC 4.6.1 20110608 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from haversine import *
>>> dms_to_float((111, 41, 0, 'SW'))
111.68333333333334
>>> dms_to_float((111,41,0,'Sw'))
-111.68333333333334

元组中有空格,答案是错误的。没有,答案是正确的。

4

2 回答 2

12

空格应该没有区别。差异是由于案例:SWvs Sw

你不在SW这里检查:

compass in ['S', 'W', 'Sw']] 

也许将其更改为:

compass.upper() in ['S', 'W', 'SW']] 
于 2011-09-25T21:00:40.273 回答
0

假设“度”与纬度或经度有关,我无法想象为什么“SW”被视为可行的选择。纬度是 N 或 S。经度是 E 或 W。请解释一下。

根据您的大小为 1 的样本,用户输入不可信。考虑检查输入,或者至少确保虚假输入会导致引发异常。你似乎喜欢单线;试试这个:

float_degrees *= {'n': 1, 's': -1, 'e': 1, 'w': -1}[compass.strip().lower()]
于 2011-09-25T21:45:42.673 回答