开发者

How can I put multiple statements in one line?

开发者 https://www.devze.com 2023-03-09 05:24 出处:网络
I know a little bit of comprehensions in Python, but they seem very hard to \'read\'. The way I see it, a compreh开发者_如何学Pythonension might accomplish the same as the following code:

I know a little bit of comprehensions in Python, but they seem very hard to 'read'. The way I see it, a compreh开发者_如何学Pythonension might accomplish the same as the following code:

for i in range(10): if i == 9: print('i equals 9')

This code is much easier to read than how comprehensions currently work, but I've noticed you can’t have two :s in one line. This brings me to:

Is there a way I can get the following example into one line?

try:
    if sam[0] != 'harry':
        print('hello',  sam)
except:
    pass

Something like this would be great:

try: if sam[0] != 'harry': print('hellp',  sam)
except:pass

But again I encounter the conflicting :s.

I'd also love to know if there's a way to run try (or something like it) without except. It seems entirely pointless that I need to put except:pass in there. It’s a wasted line.


Unfortunately, what you want is not possible with Python (which makes Python close to useless for command-line one-liner programs). Even explicit use of parentheses does not avoid the syntax exception. You can get away with a sequence of simple statements, separated by semicolon:

for i in range(10): print "foo"; print "bar"

But as soon as you add a construct that introduces an indented block (like if), you need the line break. Also,

for i in range(10): print "i equals 9" if i==9 else None

is legal and might approximate what you want.

If you are still determined to use one-liners, see the answer by elecprog.

As for the try ... except thing: It would be totally useless without the except. try says "I want to run this code, but it might throw an exception". If you don't care about the exception, leave out the try. But as soon as you put it in, you're saying "I want to handle a potential exception". The pass then says you wish to not handle it specifically. But that means your code will continue running, which it wouldn't otherwise.


You could use the built-in exec statement, eg.:

exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello',  sam) \nexcept: pass")

Where \n is a newline and \t is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.

However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.

exec is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.


You can now just use semicolons. However, you cannot use if/elif/else statements, for/while loops, and you can't define functions. The main use of this would be when using imported modules where you don't have to define any functions or use any if/elif/else/for/while statements/loops.

Here's an example that takes the artist of a song, the song name, and searches genius for the lyrics:

import bs4, requests; song = input('Input artist then song name\n'); print(bs4.BeautifulSoup(requests.get(f'https://genius.com/{song.replace(" ", "-")}-lyrics').text,'html.parser').select('.lyrics')[0].text.strip())


I do not incentivise this, but say you're on the command line, you have nothing but Python and you really need a one-liner, you can do this:

python -c "$(echo -e "a='True'\nif a : print 1")"

Here we're pre-processing \n before evaluating Python code.

That's super hacky! Don't write code like this.


I recommend not doing this...

What you are describing is not a comprehension.

PEP 8 Style Guide for Python Code, which I do recommend, has this to say on compound statements:

  • Compound statements (multiple statements on the same line) are generally discouraged.

Yes:

      if foo == 'blah':
          do_blah_thing()
      do_one()
      do_two()
      do_three()

Rather not:

      if foo == 'blah': do_blah_thing()
      do_one(); do_two(); do_three()

Here is a sample comprehension to make the distinction:

>>> [i for i in xrange(10) if i == 9]
[9]


For a python -c oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:

Suppose you would like to do something like this (very similar to your sample, including except: pass instruction):

python -c  "from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n" OUTPUT_VARIABLE __numpy_path

This will not work and produce this error:

  File "<string>", line 1
    from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n
                                                                                                                  ^
SyntaxError: unexpected character after line continuation character `

This is because the competition between Bash and Python interpretation of \n escape sequences. To solve the problem one can use the $'string' Bash syntax to force \n Bash interpretation before the Python one.

To make the example more challenging, I added a typical Python end=..\n.. specification in the Python print call: at the end you will be able to get both \n interpretations from Bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this:

python -c  $'from __future__ import print_function\ntry:\n import numpy;\n print( numpy.get_include(), end="\\n" )\n print( "Hello" )\nexcept:pass\n' OUTPUT_VARIABLE __numpy_path

That leads to the proper clean output without an error:

/Softs/anaconda/lib/python3.7/site-packages/numpy/core/include
Hello

Note: this should work as well with exec-oriented solutions, because the problem is still the same (Bash and Python interpreters competition).

Note 2: one could work around the problem by replacing some \n by some ; but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.

Note 3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, but doing a proper mixed-management of \n escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.


It’s actually possible ;-)

# Not PEP 8 compatible^
sam = ['Sam',]
try: print('hello', sam) if sam[0] != 'harry' else rais
except: pass

You can do very ugly stuff in Python like:

def o(s):return ''.join([chr(ord(n) + (13 if 'Z' < n < 'n' or 'N' > n else -13)) if n.isalpha() else n for n in s])

which is a function for ROT13 and Caesar encryption in one line.


Maybe with "and" or "or".

After false, we need to write "or".

After true we need to write "and".

Like

n = 0

def returnsfalse():
    global n
    n = n + 1
    print("false %d" % (n))
    return False

def returnstrue():
    global n
    n = n + 1
    print("true %d" % (n))
    return True

n = 0
returnsfalse() or returnsfalse() or returnsfalse() or returnstrue() and returnsfalse()

Result:

false 1
false 2
false 3
true 4
false 5

Or maybe like

(returnsfalse() or true) and (returnstrue() or true) and ...

I got here by searching Google with "how to put multiple statments in one line Python". It does not answer the question directly, but maybe somebody else needs this.


If you want it without try and except, then there is the solution.

If you are trying to print 'hello' if 'harry' in a list then the solution is:

'hello' if 'harry' in sam else ''


There is a possible PEP 8 compatible solution.

Solution to if, else

[print("i equals 9") for i in range(10) if i == 9]

Use a list generation instead of if, else.

I think this is probably a useful trick, which has already stated by comment by ThomasH. So this is a serious solution.

Solution to try, except

print("hello", sam) \
    if "sam" in locals() \
    and hasattr(sam, "__getitem__") \
    and 0 < len(sam) \
    and sam[0] != "harry" \
    else None

Try to deal with how expect would behave by an in-line if statement. This line of code is specialized to deal with the existence of sam[0], thus I couldn't resolve other general try, except cases.

This is one line of code (=w=). Though if written in exactly one-line, it could be too long to contradict PEP 8 E501. So this is a solution for fun.

  • "sam" in locals checks if sam is a valid variable in the current environment;

  • hasattr(sam, "__getitem__") checks if variable sam could be indexed by sam[n];

  • 0 < len(sam) checks if sam have more than zero items;

  • then check sam[0] != "harry".

  • Warning: This should work when type(sam) == list. Other cases were not tested. If you are sure that sam is a list, then the code would not be too lengthy:

    print("hello", sam) if 0 < len(sam) and sam[0] != "harry" else None
    

Additional Contents

As other answers (for example, Johnsyweb stated, multiple statements on one line is not preferred (PEP 8 E701). So, for any possible Pythonic (PEP 8) solution, the one-line code may have to avoid explicit if, else and try, except.

As another comment by Thomash stated, a better solution for try, except should using a wrapping function. This adds another lines of code; however, calling the function can not only check sam but also other variables:

def check_harry(name):
    try:
        print("hello", name) if name[0] != "harry" else None
    except (NameError, TypeError, IndexError):
        pass

check_harry(uncle)
check_harry(sam)

This could be a more serious solution. Note that bare except is not recommended due to PEP 8 E722. Although this line of compulsive except: pass seems to be a waste of time (and I actually usually agree with that T_T), there lies some code style consideration.


You are mixing a lot of things, which makes it hard to answer your question. The short answer is: As far as I know, what you want to do is just not possible in Python - for good reason!

The longer answer is that you should make yourself more comfortable with Python, if you want to develop in Python. Comprehensions are not hard to read. You might not be used to reading them, but you have to get used to it if you want to be a Python developer. If there is a language that fits your needs better, choose that one. If you choose Python, be prepared to solve problems in a pythonic way. Of course you are free to fight against Python, But it will not be fun! ;-)

And if you would tell us what your real problem is, you might even get a pythonic answer. "Getting something in one line" us usually not a programming problem.


Based on ThomasH's answer:

for i in range(4): print "i equals 3" if i==3 else None

Output:

None
None
None
i equals 3

I propose to update as:

for i in range(4): print("i equals 3") if i==3 else print('', end='')

Output:

i equals 3

Note, I am in Python 3 and had to use two print commands. pass after else won't work.


sam = ['harry', 'john']

print('hello ' + sam[0] if sam[0] != 'harry' else '')


Here is an example:

for i in range(80, 90): print(i, end=" ") if (i!=89) else print(i)

Output:

80 81 82 83 84 85 86 87 88 89
>>>
0

精彩评论

暂无评论...
验证码 换一张
取 消