Python 中的错误:列表索引超出范围

Error in Python : List index out of range

def item(id):
return posts.loc[posts['post_id'] == id]['title'].tolist()[0]

def get_recommendations(postid, num, indices):
idx = indices[postid]
sim_scores = list(enumerate(cosine_similarities[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
sim_scores = sim_scores[1:num+1]
# print(sim_scores)
indices = [i[0] for i in sim_scores]
print("Recommending " + str(num) + " posts similar to \"" + item(postid) + "\" ...")
return posts.iloc[indices]

这是我的代码,当我 运行 它时,我收到以下错误:

IndexError                                Traceback (most recent call last)
<ipython-input-58-54719cff7892> in <module>()
----> 1 show_recomm('5d6d39567fa40e1417a4931c', 10, indices)

1 frames
<ipython-input-45-dfd12eb7d387> in show_recomm(postid, num, indices)
      6     print(similarity_scores)
      7     indices = [i[0] for i in similarity_scores]
----> 8     print("Recommending " + str(num) + " posts similar to \"" + item(postid) + "\" ...")
      9     return posts.iloc[indices, :-1]

<ipython-input-44-6739fecf9da1> in item(id)
      1 def item(id):
----> 2     return posts.loc[data['post_id'] == id]['title'].tolist()[0]

IndexError: list index out of range

当我使用不同的 post ID 尝试该函数时出现此错误。对于一些,我得到了输出,对于其他 id,我没有。

根据我在上面看到的内容。好像是因为

data['post_id'] == id

这可能是对的,也可能是错的。你是说

def item(id):
    return posts.loc[id]['title'].tolist()[0]