gpt4 book ai didi

做 `if x in y where x.attr == val` 的 Pythonic 方式?

转载 作者:太空宇宙 更新时间:2023-11-03 11:26:23 25 4
gpt4 key购买 nike

我有一个类将多项式表示为项的集合,其中每个项都有一个系数和一个指数。我正在研究该类的 __add__ 方法,我想知道最有效的方法是什么:

def __add__(self, other):
new_terms = []
for term in self.terms:
if there is a term in other with an exponent == term.exponent
new_terms.append(Term(term.coef + other_term.coef, term.exponent))

令我印象深刻的是,我正在寻找诸如以下内容:

if x in y where x.attr == val

或者在我的具体情况下:

if x in other where x.exponent == term.exponent

有这样的东西吗?

最佳答案

在进行包含检查之前,您需要过滤列表。正如 tobias_k 所建议的那样,您可以构建一个新列表,例如

[x for x in other if x.exponent == term.exponent]

这直接在 if 语句中起作用,因为空列表是 False:

if [x for x in other if x.exponent == term.exponent]:

但这会做一些浪费工作,因为它 a) 必须构建一个新列表,并且 b) 一旦找到结果就不会短路。更好的方法是在生成器表达式中使用相同的语法:

(True for x in other if x.exponent == term.exponent)

然后您可以在 if 语句中类似地使用它,但不会做任何浪费的工作:

if next((True for x in other if x.exponent == term.exponent), False):

关于做 `if x in y where x.attr == val` 的 Pythonic 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32611356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com