理解Python
我正在读《编程集体智能》一书,下面的python代码到底是做什么的理解Python,python,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中的示例 Pr
# 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是个人到电影收视率的映射,电影收视率是姓名到收视率的另一个映射。首先,它构建了一个包含以下结果的列表:
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")
然后将它们相加。它计算
prefs[person1][item]
和prefs[person2][item]
之间差值的平方和,对于prefs
字典中的person1
中的prefs[person2][item]
,也在person2
字典中
换句话说,假设person1
和person2
对这部电影都有评级,其中person1
评级为5颗星,而person2
评级为2颗星
prefs[person1]['Ratatouille'] = 5
prefs[person2]['Ratatouille'] = 2
person1
的评分与person2
的评分之差的平方为3^2=9
它可能在计算某种类型的数据
Sum(第2行)一个列表,由第4-7行中为第11行指定的列表中定义的每个“项”计算的值组成,第13行中的条件适用于该列表。如果将对pow的调用替换为显式使用“**”求幂运算符,则可读性可能会更强一些:
sum_of_squares=sum([(prefs[person1][item]-prefs[person2][item])**2
for item in prefs[person1] if item in prefs[person2]])
提取一些不变量也有助于提高可读性:
p1_prefs = prefs[person1]
p2_prefs = prefs[person2]
sum_of_squares=sum([(p1_prefs[item]-p2_prefs[item])**2
for item in p1_prefs if item in p2_prefs])
最后,在Python的最新版本中,不需要列表理解符号,sum将接受生成器表达式,因此也可以删除[]:
sum_of_squares=sum((p1_prefs[item]-p2_prefs[item])**2
for item in p1_prefs if item in p2_prefs)
现在看起来有点直截了当了
具有讽刺意味的是,为了追求可读性,我们还进行了一些性能优化(这两项工作通常是相互排斥的):
- 从循环中提取不变量
- 将函数调用pow替换为“**”运算符的内联求值
- 删除了不必要的列表结构
这是一门很棒的语言还是什么 此外,在Python的最新版本中,不需要在整个列表之外使用“[”和“]”。如果缺少这些值,Python就不会麻烦实际创建列表,而是在计算它们时将这些值相加。因此,这是两个值之间的公共分数差的平方和,对吗?是的(我需要在这里添加更多字母,然后才能提交)。
sum_of_squares=sum((p1_prefs[item]-p2_prefs[item])**2
for item in p1_prefs if item in p2_prefs)