python - 为什么 Python 元组中的空格很重要?

标签 python iterable-unpacking

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

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

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

最佳答案

空格应该没有区别。区别在于大小写:SWSw

你不检查这里的SW:

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

也许改成这样:

compass.upper() in ['S', 'W', 'SW']] 

关于python - 为什么 Python 元组中的空格很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7548562/

相关文章:

python - *为什么* multiprocessing 序列化我的函数和闭包?

python - py2exe:排除要导入其所有部分的包的部分

python - 仅将一些元组元素扩展到变量列表

scala - 映射操作中的元组解包

python - 将字典传递给具有 base_estimator 特征的 sklearn 分类器

python - 在 Python 赋值运算符中使用逗号和下划线的含义?

python - Pandas — 在 MultiIndex 上使用部分切片设置值

python - "sh: sysctl Command not Found "对于运行 cron 作业的 Mac OS X

python - numpy 数组中所有值的平方根,保留符号

python - 可迭代拆包的默认值