python sum 函数中可以使用条件语句吗

查看:281
本文介绍了python 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 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 prefs[person1] if item in prefs[person2]])

  return 1/(1+sum_of_squares)

比较困惑的是下面这段代码,为什么sum里面可以写for 循环呢,这个是什么意思,为什么我写了个类似的函数就会报错

sum([pow(prefs[person1][item]-prefs[person2][item],2) 
                          for item in prefs[person1] if item in prefs[person2]])

解决方案

sum接受的第一个参数是个iterable。楼主想知道这个for循环的含义,要去查看一下生成器以及生成器相关的语法糖,这里给楼主一个简单的例子[i for i in range(5)] # 结果为[0,1,2,3,4]

这篇关于python sum 函数中可以使用条件语句吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆