python的map/reduce的若干问题

问题一: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)


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值