問題一: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的科學與工程計算作業
接下來的代碼解決第一問:
先囉嗦兩句,一開始用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)