python - 从列表中返回对象,从列表中的其他对象计算出的特定条件是正确的

标签 python

<分区>

我有以下代码

 last_question = max(answer.question_id for answer in answers)

我不仅需要检索最大的 question_id,还需要检索包含此 question_idanswer 对象。我可以用下一个代码来完成(假设 answers 非空):

max_answer = answers[0]
for answer in answers:
     if answer.question_id > max_answer.question_id:
         max_answer = answer
last_question = max_answer.question_id

但是我可以用 Python 的方式缩短它吗?

最佳答案

您可以使用 maxkey 参数功能:

max_answer = max(answers, key=lambda q: q.question_id)

关于python - 从列表中返回对象,从列表中的其他对象计算出的特定条件是正确的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35114505/

相关文章:

python - 如何按数字顺序导入图像?

python - 我如何让这个文本动画在pygame中显示

python - python 递归目录树

python - 在代码高尔夫中耗尽生成器的最短代码

python - django - DRF 中的登录 View

python - 如何从 Tkinter Text Widget 获取输入?

python 和 mechanize - 查看选择字段中的选项

python - drawControl 未收到正确的 QStyleOption

python - 使用 'fixed points' 在 Python 中插入数据

python - 从 setup.py 构建一个万向轮