Print “Foo” if an element is in a list

左心房为你撑大大i 提交于 2019-12-25 02:22:45

问题


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)


回答1:


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.




回答2:


l = [1, 2, 3]
x = 1
if x in l: print "Foo"

I'm not being a smart ass, this is the way to do it in one line. Or, if you're using Python3:

if x in l: print("Foo")



回答3:


Getting rid of the shortcomings of print as a statement in Python2.x using from __future__ import print_function is the first step. Then the following all work:

x in l and (lambda: print("yes"))()       # what an overkill!
(x in l or print("no")) and print("yes")  # note the order, print returns None
print("yes") if x in l else print("no")   # typical A if Cond else Y
print("yes" if x in l else "no")          # a more condensed form

For even more fun, if you're into this, you can consider this - prints and returns True or False, depending on the x in l condition (to get the False I used the double not):

def check_and_print(x, l):
    return x in l and not print("yes") or not not print("no")

That was ugly. To make the print transparent, you could define 2 other version of print, which return True or False. This could actually be useful for logging:

def trueprint(*args, **kwargs):
    print(*args, **kwargs)
    return True

def falseprint(*args, **kwargs):
    return not trueprint(*args, **kwargs)

result = x in l and trueprint("yes") or falseprint("no")



回答4:


  1. If you want to print something different in both true and false cases, use a conditional expression to create the value to print: print ('foo' if x in l else 'bar').

  2. If you just want a function in Python 2 that outputs, you can try sys.stdout.write (after you first import sys of course), but keep in mind that this is nowhere near as flexible; here you're treating the standard output as a file-like object (which it is).

  3. lambda almost certainly buys you nothing here.

  4. Using and-or chaining tricks is incredibly un-Pythonic. The fact that people struggled with these hacks anyway, knowing how awful they were, was exactly why those conditional expressions from point 1 were added to the language. There was a lot of discussion regarding syntax.



来源:https://stackoverflow.com/questions/9345250/print-foo-if-an-element-is-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!