python中的“POST for loop”是怎么回事?--Python noob
我理解下面的代码,除了下面的sum函数调用。我不明白求和函数到底接受什么作为其参数的逻辑?那里的循环是什么?那是什么东西python中的“POST for loop”是怎么回事?--Python noob,python,pyscripter,Python,Pyscripter,我理解下面的代码,除了下面的sum函数调用。我不明白求和函数到底接受什么作为其参数的逻辑?那里的循环是什么?那是什么东西 def sim_distance(prefs,person1,person2): # Get the list of shared_items si={} for item in prefs[person1]: if item in prefs[person2]: si[item]=1 # if they have no ratings in com
def sim_distance(prefs,person1,person2):
# Get the list of shared_items
si={}
for item in prefs[person1]:
if item in prefs[person2]: si[item]=1
# if they have no ratings in common, return 0
if len(si)==0: return 0
# Add up the squares of all the differences
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
for item in si])
return 1/(1+sum_of_squares)
这只是一个-所以您的“for”循环用于构建一个以2为幂的diff值列表
这是非常相似的:
lVals = []
for item in si:
lVals.append(pow(prefs[person1][item]-prefs[person2][item],2))
sum_of_squares = sum(lVals)
这只是一个-所以您的“for”循环用于构建一个以2为幂的diff值列表
这是非常相似的:
lVals = []
for item in si:
lVals.append(pow(prefs[person1][item]-prefs[person2][item],2))
sum_of_squares = sum(lVals)
所以有两个概念在起作用-总和和列表理解
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
for item in si])
首先,列表理解
[pow(prefs[person1][item]-prefs[person2][item],2) for item in si]
这可以分解为如下所示的for循环:
result_list = [] # Note that this is implicitly created
for item in si:
result_list.append(pow(prefs[person1][item]-prefs[person2][item], 2))
它通过在每次迭代中运行pow函数,使用si中的每个项并将结果附加到result_列表中,来创建一个值列表。假设循环的结果类似于[1,2,3,4]——现在sum所做的就是对列表中的每个元素求和并返回结果
关于sum函数接受什么作为参数的问题,它正在寻找一个iterable,它是可以在字符串、列表、字典的键/值等上迭代的任何东西。。就像您在for循环中看到的一样,sum在本例中添加iterable列表中的每个项并返回总数。还有一个可选的开始参数,但我会首先关注基本功能的理解:因此有两个概念在起作用-总和和列表理解
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
for item in si])
首先,列表理解
[pow(prefs[person1][item]-prefs[person2][item],2) for item in si]
这可以分解为如下所示的for循环:
result_list = [] # Note that this is implicitly created
for item in si:
result_list.append(pow(prefs[person1][item]-prefs[person2][item], 2))
它通过在每次迭代中运行pow函数,使用si中的每个项并将结果附加到result_列表中,来创建一个值列表。假设循环的结果类似于[1,2,3,4]——现在sum所做的就是对列表中的每个元素求和并返回结果
关于sum函数接受什么作为参数的问题,它正在寻找一个iterable,它是可以在字符串、列表、字典的键/值等上迭代的任何东西。。就像您在for循环中看到的一样,sum在本例中添加iterable列表中的每个项并返回总数。还有一个可选的开始参数,但我将首先重点了解基本功能: