【问题标题】:The difference between map, enumerate and lambda in python 3.4 and python 2.7? [duplicate]python 3.4和python 2.7中map、enumerate和lambda的区别? [复制]
【发布时间】:2017-01-30 22:28:39
【问题描述】:

我正在做一个项目,我必须计算 Dirichlets 在数据集上的分布。我在this tutorial 中找到了一些代码,由Benjamin Bengfort 开发。

作为一个培训示例,我开发了这个基本代码来理解和测试给定链接中的代码:

from collections import Counter

train_list = [1,2,1,2,1,3,4,1,2,3]
counter = Counter(train_list)
votes = [counter.get(n,0) for n in range(1,5)]
prior = [2,2,2,2]
posterior = map(sum, zip(votes, prior))
weights = map(lambda i: (i[0]+1)*i[1], enumerate(posterior))
N = sum(posterior)
print(float(sum(weights)) / N)

我在 python 3.5 和 python 2.7 中都运行了代码。
无论我是否更改 train_list,我在 python 3.5 中总是得到相同的结果,等于零。
但是在 python 2.7 中,我得到了一个浮点数,我猜这恰好是正确的答案,因为每当我修改 train_list 中的值时它都会改变。
不知道为什么会这样?
原因可能是 python 2.7 和 python 3.5 之间的 map、lambda 或 enumerate 函数的过程不同。
如果有人可以帮助我修复 python 3.5 中的代码,将不胜感激。

【问题讨论】:

    标签: python-2.7 lambda python-3.5 enumerate


    【解决方案1】:

    我找到了答案。
    感谢Josh Lee,我将代码修改为这个,它在 python 3.5 和 python 2.7 中返回了相同的值:

    from collections import Counter
    
    train_list = [1,2,1,2,1,3,4,1,2,3]
    counter = Counter(train_list)
    votes = [counter.get(n,0) for n in range(1,5)]
    prior = [2,2,2,2]
    posterior = list(map(sum, zip(votes, prior)))
    weights = map(lambda i: (i[0]+1)*i[1], enumerate(posterior))
    N = sum(posterior)
    print(float(sum(weights)) / N)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多