为什么Python元组中的空间很重要?

2024-06-02 05:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: to答案compassdmsswfloattmp元组
2条回答

空间应该没什么区别。区别是由于这种情况:SWvsSw。在

此处不检查SW

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

或许可以改成这样:

^{pr2}$

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

根据您的1号样本,用户输入是不可信的。考虑检查输入,或者至少确保伪输入将引发异常。你似乎喜欢一句话;试试这个:

float_degrees *= {'n': 1, 's': -1, 'e': 1, 'w': -1}[compass.strip().lower()]

相关问题 更多 >