这个很难说。它来自试图了解内联函数。
这个问题是我提出的另一个问题的副产品:Evaluating input function inline, in order to append input or placeholder to a list
我希望此代码有效。这个想法是,在不调用两次函数的情况下评估函数的输出-如果选择项等于设置值,则应将选择项附加到列表中:
import random
def returner():
choices = ['cat', 'dog']
return random.choice(choices)
list = []
list.append(returner() if returner() == 'dog' else 'got the cat in the bag')
问题是,在上面我两次调用了该函数。如果是用户输入,那么提示用户两次就不会那么好。所以我想我可以做:
list.append(x = returner() if x == 'dog' else 'got the cat in the bag')
是否可以执行上述操作?
答案 0 :(得分:2)
如果您知道自己要与之进行比较的话
list = []
list.append("dog" if returner() == "dog" else "got cat in the bag")
否则,您将不得不做
list = []
r = returner()
list.append(r if r == 'dog' else 'got the cat in the bag')
无论哪种情况,实际上您都可以通过更改这两行来使代码更紧凑
list = []
list.append("dog" if returner() == "dog" else "got cat in the bag")
进入
list = ["dog" if returner() == "dog" else "got cat in the bag"]
答案 1 :(得分:1)
您可以推迟对returner()
的调用,并将其结果放入一个(1元素)列表中,可以使用:
import random
def returner():
choices = ['cat', 'dog']
return random.choice(choices)
l = [x if x == "dog" else 'got the cat in the bag' for x in [returner()] ]
print(l)
但是我会很犹豫-预先存储(一个)结果的方法更加简洁:
choi = returner()
l = [choi if choi == "dog" else 'got the cat in the bag' ]
但是,如果需要倍数,第一种方法会起作用:
l = [x if x == "dog" else 'got the cat in the bag'
for x in [returner() for _ in range(20)] ]