打印“Foo"如果一个元素在列表中 [英] Print "Foo" if an element is in a list

查看:53
本文介绍了打印“Foo"如果一个元素在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过:

<预><代码>>>>l = [1,2,3]>>>x = 1>>>x 在 l 和 lambda 中:print("Foo")x in l &&打印Horray"^语法错误:无效语法

通过谷歌搜索发现 printpython2 中的一个语句,而它是 python3 中的一个函数.但是,我已经尝试了上面在 python3 中剪下的代码,它抛出了 SyntaxError 异常.

关于如何在一行中完成的任何想法?(可读性或谷歌编程实践在这里不是问题)

解决方案

lambda 创建了一个 lambda.它需要被调用来执行.你不能那样做,因为 Python 不允许在这个上下文中使用语句,只允许表达式(包括函数调用).

要在 Python 2.x 中使 print 成为一个函数,请尝试:

from __future__ import print_functionx in l 和 print('foo')

不过要小心.如果您尝试:

x in l and print('foo') 或 print('bar')

不行,因为print返回None,所以第一个and表达式为False,所以print都会被执行.在 Python 3.x 中,您不需要导入.

如果您不会有复杂的短路(即只有一个 andor),或者您知道您的函数或表达式不会让短路 -电路逻辑,代码没有任何问题.否则,请尝试非短路 1-liner:

print('foo') if x in l else print('bar')

仅当条件为 True 的概率/期望大大高于为 False 时,才推荐使用此形式.否则,简单的旧 if-else 是要走的路.

I have tried:

>>> l = [1,2,3]
>>> x = 1
>>> x in l and lambda: print("Foo")
    x in l && print "Horray"
            ^
SyntaxError: invalid syntax

A bit of googling revealed that print is a statement in python2 whereas it's a function in python3. But, I have tried the above snipped in python3 and it throws SyntaxError exception.

Any idea on how can I do it in one line? (Readability or google programming practice is not an issue here)

解决方案

lambda creates, well a lambda. It needs to be called to execute it. You cannot do this that way, because Python doesn't allow statements in this context, only expressions (including function calls).

To make print a function in Python 2.x, try:

from __future__ import print_function
x in l and print('foo')

Be wary though. If you try:

x in l and print('foo') or print('bar')

it won't work, because print returns None, so the first and expression is False, so both prints will be executed. In Python 3.x you don't need the import.

If you won't have complex short-circuiting (i.e. just one and or or), or you know your functions or expressions won't surprise the short-circuiting logic, there's nothing wrong with the code. Otherwise, try the non-short-circuiting 1-liner:

print('foo') if x in l else print('bar')

This form is recommended only if the probability/expectation of the conditional to be True is vastly higher than being False. Otherwise, plain good-old if-else is the way to go.

这篇关于打印“Foo"如果一个元素在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆