isgood 发表于 2018-8-14 06:28:19

Python3下map函数的问题

  今天在群里有人问题,他的Python程序在家里运行好好的,但在公司一运行,就出问题了,查来查去查不出来,于是我就把他的程序调转过来看了一下,发现又是Python2.7与Python3的问题。
  代码是做了一个可定义任意位数的水仙花数函数
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,n)
  
      if sum == i:
  
            print(i)
  
if __name__=="__main__":
  
    n = int(input("请输入正整数的位数:"))
  
    fn(n)
  在Python2.7下面运行结果:
  请输入正整数的位数:5
  54748
  92727
  93084
  Process finished with exit code 0
  但在Python3下面运行结果:
  请输入正整数的位数: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下面运行结果:
  
  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下面运行结果就正常了:  
  Process finished with exit code 0
  之前就发布过一篇关于:Python 2.7.x 和 3.x 版本区别小结
  基于两个版本的不一样,如果不知道将要把代码部署到哪个版本下,可以暂时在代码里加入检查版本号的代码:
  import platform
  platform.python_version()
  通过判断版本号来临时调整差异,不过现在只是过渡,以后大家都使用Python3以下版本后,就应该不需要这样做了。
页: [1]
查看完整版本: Python3下map函数的问题