问题一:print()的参数是一个list的转化函数或者是一个list变量,结果不一样。
先看代码:
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
list_r = list(r)
print(r)
print(list(r))
print(list_r)
map函数格式为:
map(fun,list)
map函数的作用是 用fun()函数依次对list这个可迭代对象Iterator作用,并返回一个新的Iterator。
上述函数的作用就是对 序列 1-9 取平方数,返回这些数的平方数的list形式。
但是上述代码的结果是:
print(list(r)) 打印出了一个空的list
print(list_r) 打印出了正确的结果
现在的能力还没办法解释,以后再慢慢看看吧。
问题二:在map(fun,list)的fun中打印变量,有点不理解
还是看代码
def f(x):
print(x)
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
函数 f() 里面有一行代码:
print(x)
按照道理来说,运行上述代码,应该打印出来才对的。毕竟有print(x)命令
但是,竟然没有。
然后我在代码最后一行加上:
def f(x):
print(x)
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
list_r = list(r)
结果正确。尼玛这TM什么玩意啊。
为什么!!!
问题三:室友zps的科学与工程计算作业
![](https://i-blog.csdnimg.cn/blog_migrate/707770c388b2bb4dde09a32afd582e8e.png)
接下来的代码解决第一问:
先啰嗦两句,一开始用for循环,后来感觉太low了,改成了map()函数来运行,然后就遇到了神之bug。主要问题在我有没有加上这一行代码:
list_mmp = list(mmp)
很神奇啊,不加下面这一行,resultList,xList,errorList 啥也出不来,只有加这一行才好使。
我一开始以为没有加上global,后来发现list类型的数据结构是全局变量,不用加global,也可以被函数当成全局变量。
但是加上global还是不行,后来瞎调才发现要写上
list_mmp = list(mmp)
可是这他娘的是为什么???
有时间我一定要看看map/reduce的python源代码。
import math
import numpy as np
import matplotlib.pyplot as plt
import csv
eValue=2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
eValue=2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
def plotLine(x, y):
plt.scatter(x, y, color="m",marker="o", s=30)
plt.plot(x, y, color="g")
# putting labels
plt.xlabel('x')
plt.ylabel('y')
# function to show plot
plt.show()
resultList = []
xList = []
errorList=[]
# for x in range(1 , 1000):
# result = math.pow( 1+(1/x),x)
# resultList.append(result)
# xList.append(x)
# if abs(2.71828182845-result) >0.1:
# errorList.append(result)
# #print(result)
def fun1(x):
result = math.pow(1+(1/x),x)
resultList.append(result)
xList.append(x)
if abs(2.71828182845-result) >0.1:
errorList.append(result)
mmp = map(fun1,range(1,100))
#很神奇啊,不加下面这一行,resultList,xList,errorList 啥也出不来,只有加这一行才好使。
list_mmp = list(mmp)
plotLine(xList, resultList)
print(resultList)
print(xList)
print(errorList)