问题:如何将多个语句放在一行中?

我不确定要确切地考虑这个问题的标题,如果不太明确,编码高尔夫似乎是合适的。

我对python有一点了解,但似乎很难“阅读”。我的理解方式可能与以下代码相同:

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

这段代码比当前的理解方法更容易阅读,但是我注意到您不能在一行中包含两个“:”……这也给我带来了……

我的问题:

有什么办法可以使下面的示例进入一行。

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

这样的事情会很棒:

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

但是我又遇到了冲突的’:’,我也很想知道是否有一种方法可以不加尝试地运行try(或类似的东西),我似乎完全没有意义,我只需要在其中放入else:pass即可。它是一条浪费的线路。

谢谢您的输入…这里有一个笑脸:D

I wasn’t sure under what title to ponder this question exactly, coding golf seems appropriate if a bit unspecific.

I know a little bit of comprehensions in python but they seem very hard to ‘read’. The way I see it, a comprehension 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 cant have two ‘:’ in one line … this brings me too…

my question:

Is there any 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 ‘:’ 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. its a wasted line.

Thank you for you input … and here have a smiley :D


回答 0

不幸的是,Python无法实现您想要的(这使得Python对命令行一线程序几乎无效)。甚至显式使用括号也无法避免语法异常。您可以摆脱一系列用分号分隔的简单语句:

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

但是,一旦添加了引入缩进的块的构造(如if),就需要换行。也,

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

是合法的,可能与您想要的近似。

至于try ... except事情:没有,那将完全没有excepttry说“我想运行此代码,但可能会引发异常”。如果您不在乎该异常,请不要使用try。但是,一旦输入,您就说“我想处理潜在的异常”。该pass那么说,你要没有特别处理。但这意味着您的代码将继续运行,否则就不会继续运行。

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 semi-colon:

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.

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 away 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.


回答 1

您可以使用内置的exec语句,例如:

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

哪里\n是换行符,\t用作缩进(选项卡)。
另外,您应该计算使用的空间,以便缩进完全匹配。

但是,正如所有其他答案已经说过的那样,这仅在您确实需要将其放在一行上时才使用。

exec 这是一个非常危险的声明(尤其是在构建Web应用程序时),因为它允许执行任意Python代码。

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.


回答 2

我建议要这样做…

您所描述的不是理解力。

强烈建议使用PEP 8 Python代码样式指南在复合语句中这样说:

  • 通常不建议使用复合语句(同一行上的多个语句)。

是:

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

而不是:

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

以下是进行区分的示例理解:

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

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]

回答 3

是的,这篇文章已有8年历史了,但是如果有人来这里寻找答案:您现在可以只使用分号。但是,您不能使用if / elif / else语句,for / while循环,也不能定义函数。它的主要用途是在使用导入的模块时,您不必定义任何函数或使用任何if / elif / else / for / while语句/循环。

这是一个示例,该示例采用歌曲的歌手,歌曲名称并在天才中搜索歌词:

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())

Yes this post is 8 years old, but incase someone comes on here also looking for an answer: you can now just use semicolons. However, you cannot use if/elif/else staments, 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())

回答 4

我不会对此进行激励,但是说您在命令行上,除了Python之外什么都没有,并且您确实需要一个衬套,您可以这样做:

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

我们在这里所做的是\n在评估Python代码之前进行预处理。

超级骇客!不要写这样的代码。

I do not incentivise this, but say you’re on 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")"

What we’re doing here is pre-processing \n before evaluating Python code.

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


回答 5

可能带有“和”或“或”

错误后需要写“或”

确实需要写“和”之后

喜欢

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()

结果:

false 1
false 2
false 3
true 4
false 5

也许像

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

通过搜索谷歌“如何在一行python中放置多个语句”到达此处,而不是直接回答问题,也许其他人需要这个。

maybe with “and” or “or”

after false need to write “or”

after true 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 ...

got here by searching google “how to put multiple statments in one line python”, not answers question directly, maybe somebody else needs this.


回答 6

对于python -c面向解决方案,并在您使用Bash shell的情况下,可以的,您可以使用一个简单的单行语法,例如以下示例:

假设您想执行以下操作(与示例非常相似,包括except: pass说明):

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

这将无法工作并产生此错误:

  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 `

这是因为Bash和Python之间的竞争是\n转义序列的解释。要解决此问题,可以使用$'string'Bash语法\n在Python之前强制使用Bash解释。为了使示例更具挑战性,我end=..\n..在Python打印调用中添加了一个典型的Python 规范:最后,您将能够\n从bash和Python一起获得BOTH 解释,每个解释都涉及其关注的文本。这样最终正确的解决方案是这样的:

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

这将导致正确的干净输出而没有错误:

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

注意:这对于exec面向解决方案应该也能正常工作,因为问题仍然存在(Bash和Python解释器的竞争)。

注2:人们可以通过更换一些解决该问题\n的一些;,但它不会工作任何时候(取决于Python的结构),而我的解决方案允许始终以“一行”任何一件经典的多行Python程序。

注意3:当然,在使用单行代码时,必须始终注意Python的空格和缩进,因为实际上我们并不是严格意义上的“单行代码”,但是\n在bash和Python之间进行适当的转义序列混合管理。这就是我们可以处理任何经典的多行Python程序的方式。解决方案示例也对此进行了说明。

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 with no 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).

Note2: one could workaround 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.

Note3: 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.


回答 7

您正在混合很多东西,这使得很难回答您的问题。简短的答案是:据我所知,您想要做的事在Python中是不可能的-这是有充分理由的!

更长的答案是,如果您想用Python开发,则应该使自己对Python更加适应。理解并不难读。您可能不习惯阅读它们,但是如果您想成为Python开发人员,就必须习惯它。如果有一种语言更适合您的需求,请选择该语言。如果选择Python,请准备以pythonic的方式解决问题。当然,您可以自由地与Python对抗,但这不会很有趣!;-)

如果您告诉我们您真正的问题是什么,您甚至可能会得到一个pythonic答案。“一站式获取”通常不是编程问题。

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.


回答 8

它有可能实现;-)

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

您可以在python中做非常丑陋的事情,例如:

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

这是用于以99个字符为一行的rot13 / cesa加密的功能。

Its acctualy possible ;-)

# not pep8 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)+(13if'Z'<n<'n'or'N'>n else-13))if n.isalpha()else n for n in s])

which is function for rot13/cesa encryption in one line with 99 characters.


回答 9

这是一个例子:

对于范围在(80,90)中的i:如果(i!= 89)则print(i,end =“”)否则print(i)

输出:80 81 82 83 84 85 86 87 88 89

>

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

>


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。