For loop with function in Python -Code not 运行 list but 运行 in standalone

For loop with function in Python -Code not running with list but running in standalone

def predict_movies(mnames) 正在完善并提供输出数据框。但是当试图将输入参数作为 mnames 列表传递时,它给出了输出。它也没有抛出错误。看起来我正在犯一个微不足道的错误。单个输入参数的相同代码运行良好。输入列表的元素在 function.Your 帮助中指出的所有相关文件中都可用。 代码块如下。

movie_names_for_predictions=['Return of the Jedi (1983)','Wrong Trousers, The (1993)','Pink Floyd - The Wall (1982)','North by Northwest (1959)']

for mnames in range(0,len(movie_names_for_predictions)):
       
        def predict_movies(mnames):
                movie_user_ratings=movieRatings[mnames]
                similar_to_movie=movieRatings.corrwith(movie_user_ratings)
                corr_movie=pd.DataFrame(similar_to_movie,columns=['correlation'])
                corr_movie.dropna(inplace=True)
                corr_movie=corr_movie.join(ratings_compiled['Number of ratings'])
                predictions=corr_movie[corr_movie['Number of ratings']>100].sort_values('correlation',ascending=False)
                return print(mnames,predictions)

你每次都在循环中重新声明你的函数,这是不必要的。您可以在 运行 循环之前声明您的函数并在每次迭代中调用它。

def predict_movies(mname):
    movie_user_ratings = movieRatings[mname]
    similar_to_movie = movieRatings.corrwith(movie_user_ratings)
    corr_movie = pd.DataFrame(similar_to_movie, columns=['correlation'])
    corr_movie.dropna(inplace=True)
    corr_movie = corr_movie.join(ratings_compiled['Number of ratings'])
    predictions = corr_movie[corr_movie['Number of ratings'] > 100].sort_values('correlation', ascending=False)
    # Don't return a print statement
    return predictions

movie_names_for_predictions = ['Return of the Jedi (1983)', 'Wrong Trousers, The (1993)', 'Pink Floyd - The Wall (1982)', 'North by Northwest (1959)']

# Less boilerplate code for looping
for mname in movie_names_for_predictions:
    predictions = predict_movies(mname)
    print(mname, predictions)