今天在群里有人问题,他的Python程序在家里运行好好的,但在公司一运行,就出问题了,查来查去查不出来,因而我就把他的程序调转过来看了一下,发现又是Python2.7与Python3的问题。
代码是作了一个可定义任意位数的水仙花数函数python
def fn(n): rs = [] for i in range(pow(10,n-1),pow(10,n)): rs = map(int, str(i)) sum = 0 for k in range(0,len(rs)): sum = sum + pow(rs[k],n) if sum == i: print(i) if __name__=="__main__": n = int(input("请输入正整数的位数:")) fn(n)
在Python2.7下面运行结果:
less
请输入正整数的位数:5ide
54748函数
92727spa
93084code
Process finished with exit code 0orm
但在Python3下面运行结果:
blog
请输入正整数的位数:5文档
Traceback (most recent call last):部署
File "D:/Program Files/JetBrains/PyCharm 2017.1.5/myPY/myPYPro/lesson001.py", line 18, in <module>
fn(n)
File "D:/Program Files/JetBrains/PyCharm 2017.1.5/myPY/myPYPro/lesson001.py", line 11, in fn
for k in range(0,len(rs)):
TypeError: object of type 'map' has no len()
Process finished with exit code 1
由于提示是:TypeError: object of type 'map' has no len()
因此直接把代码简化,输出list看看
简化代码以下:
rs = [] for i in range(100,1000): rs = map(int, str(i)) print(rs)
在Python2.7下面运行结果:
[9, 9, 9]
Process finished with exit code 0
但在Python3下面运行结果:
<map object at 0x00C6E530>
Process finished with exit code 0
好吧,这就明白了,Python3下发生的一些新的变化,再查了一下文档,发现加入list就能够正常了
在Python3中,rs = map(int, str(i)) 要改为:rs = list(map(int, str(i)))
则简化代码要改为以下:
rs = [] for i in range(100,1000): rs = list(map(int, str(i))) print(rs)
Python3下面运行结果就正常了:
以前就发布过一篇关于:Python 2.7.x 和 3.x 版本区别小结
基于两个版本的不同,若是不知道将要把代码部署到哪一个版本下,能够暂时在代码里加入检查版本号的代码:
import platform
platform.python_version()
经过判断版本号来临时调整差别,不过如今只是过渡,之后你们都使用Python3如下版本后,就应该不须要这样作了。