如何在一行中放置多个语句? [英] How to put multiple statements in one line?
问题描述
我不确定在什么标题下准确地思考这个问题,如果有点不具体的话,编码高尔夫似乎是合适的.
I wasn't sure under what title to ponder this question exactly, coding golf seems appropriate if a bit unspecific.
我对python有一些理解,但它们似乎很难阅读".在我看来,理解可能与以下代码相同:
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...
有什么办法可以将下面的例子放到一行中吗?
Is there any way I can get the following example into ONE LINE?
try:
if sam[0] != 'harry':
print('hello', sam)
except:
pass
这样的事情会很棒:
try: if sam[0] != 'harry': print('hellp', sam)
except:pass
但是我又遇到了冲突的:
我也很想知道是否有一种方法可以在没有 except
的情况下运行 try
(或类似的东西),我需要把 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.
推荐答案
不幸的是,Python 无法实现您想要的(这使得 Python 对于命令行单行程序几乎毫无用处).即使显式使用括号也不能避免语法异常.您可以使用以分号分隔的一系列简单语句:
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"
但是,一旦您添加了一个引入缩进块的构造(如 if
),您就需要换行符.还有,
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.
至于 try ... except
事情:没有 except
将完全没用.try
说我想运行这段代码,但它可能会抛出异常".如果您不关心异常,请不要使用 try
.但是一旦你把它放进去,你就会说我想处理一个潜在的异常".pass
然后表示您不希望专门处理它.但这意味着您的代码将继续运行,否则就不会.
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.
这篇关于如何在一行中放置多个语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!