理解Python

2024-04-28 21:56:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读《编程集体智能》一书,下面的python代码到底是做什么的?在

  # Add up the squares of all the differences 
  sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) 
                      for item in prefs[person1] if item in prefs[person2]]) 

我正在尝试使用Java中的示例。在

Prefs是个人与电影收视率之间的映射,而电影分级则是姓名与收视率的另一个映射。在


Tags: ofthe代码inadd智能编程item
3条回答

如果将对pow的调用替换为显式使用“**”求幂运算符,这可能是一个更具可读性的

sum_of_squares=sum([(prefs[person1][item]-prefs[person2][item])**2
                   for item in prefs[person1] if item in prefs[person2]])

去掉一些不变量也有助于提高可读性:

^{pr2}$

最后,在Python的理解列表中,还可以去掉一个最新版本的表达式[,所以最终也不需要接受Python的sum:

sum_of_squares=sum((p1_prefs[item]-p2_prefs[item])**2
                      for item in p1_prefs if item in p2_prefs)

现在看起来更直截了当了。在

具有讽刺意味的是,为了追求可读性,我们还进行了一些性能优化(两种通常互斥的努力):

  • 从循环中取出不变量
  • 将函数调用pow替换为“**”运算符的内联求值
  • 删除了不必要的列表结构

这是伟大的语言还是什么?!在

01 sum_of_squares =
02 sum(
03  [
04      pow(
05         prefs[person1][item]-prefs[person2][item],
06         2
07      ) 
08    for
09       item
10    in
11       prefs[person1]
12    if
13       item in prefs[person2]
14  ]
15 )

Sum(第2行)一个列表,由第4-7行中为第11行指定的列表中定义的每个“项”计算的值组成,第13行的条件为真。在

首先,它构建一个包含以下结果的列表:

for each item in prefs for person1:
    if that is also an item in the prefs for person2:
        find the difference between the number of prefs for that item for the two people
        and square it (Math.pow(x,2) is "x squared")

然后再加起来。在

相关问题 更多 >