问题:如何编写内联if语句以进行打印?

我仅在将布尔变量设置为时才需要打印一些内容True。因此,看完这个之后,我尝试了一个简单的示例:

>>> a = 100
>>> b = True
>>> print a if b
  File "<stdin>", line 1
    print a if b
             ^
SyntaxError: invalid syntax  

如果我写的话也是一样print a if b==True

我在这里想念什么?

I need to print some stuff only when a boolean variable is set to True. So, after looking at this, I tried with a simple example:

>>> a = 100
>>> b = True
>>> print a if b
  File "<stdin>", line 1
    print a if b
             ^
SyntaxError: invalid syntax  

Same thing if I write print a if b==True.

What am I missing here?


回答 0

Python不不会有拖尾if 声明

ifPython 有两种:

  1. if 声明:

    if condition: statement
    if condition:
        block
    
  2. if 表达式(在Python 2.5中引入)

    expression_if_true if condition else expression_if_false

请注意,两者print ab = a都是陈述。只有a一部分是表达。所以如果你写

print a if b else 0

它的意思是

print (a if b else 0)

当你写的时候

x = a if b else 0

它的意思是

x = (a if b else 0)

现在,如果没有else子句,它将打印/分配什么?打印/分配仍然存在

请注意,如果您不希望它存在,您总是可以if在一行上编写常规语句,尽管它的可读性较差,并且确实没有理由避免使用两行变体。

Python does not have a trailing if statement.

There are two kinds of if in Python:

  1. if statement:

    if condition: statement
    if condition:
        block
    
  2. if expression (introduced in Python 2.5)

    expression_if_true if condition else expression_if_false
    

And note, that both print a and b = a are statements. Only the a part is an expression. So if you write

print a if b else 0

it means

print (a if b else 0)

and similarly when you write

x = a if b else 0

it means

x = (a if b else 0)

Now what would it print/assign if there was no else clause? The print/assignment is still there.

And note, that if you don’t want it to be there, you can always write the regular if statement on a single line, though it’s less readable and there is really no reason to avoid the two-line variant.


回答 1

内联if-else EXPRESSION必须始终包含else子句,例如:

a = 1 if b else 0

如果您想保持’a’变量值不变-修改旧的’a’值(语法要求中还需要其他):

a = 1 if b else a

这段代码留下一个不变当b转弯是假的。

Inline if-else EXPRESSION must always contain else clause, e.g:

a = 1 if b else 0

If you want to leave your ‘a’ variable value unchanged – assing old ‘a’ value (else is still required by syntax demands):

a = 1 if b else a

This piece of code leaves a unchanged when b turns to be False.


回答 2

‘else’语句是强制性的。您可以执行以下操作:

>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>> 

编辑:

或者,根据您的需要,您可以尝试:

>>> if b: print(a)

The ‘else’ statement is mandatory. You can do stuff like this :

>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>> 

EDIT:

Or, depending of your needs, you may try:

>>> if b: print(a)

回答 3

如果您不想这样做,from __future__ import print_function可以执行以下操作:

a = 100
b = True
print a if b else "",  # Note the comma!
print "see no new line"

哪些打印:

100 see no new line

如果您不反对from __future__ import print_function或使用python 3或更高版本:

from __future__ import print_function
a = False
b = 100
print(b if a else "", end = "")

添加else是您需要进行的唯一更改,以使您的代码在语法上正确无误,您需要条件条件表达式中的else(“如果else阻塞,则行内”)

我没有使用None0与线程中的其他线程一样使用过的None/0原因是,使用会导致程序进入print Noneprint 0处于bis 的情况False

如果您想阅读有关此主题的内容,我提供了指向该功能已添加到Python的补丁程序的发行说明的链接

上面的“模式”与PEP 308中显示的模式非常相似:

这种语法可能看起来很奇怪而且倒退。为什么条件出现在表达式的中间,而不是C的c的前面?x:y?通过将新语法应用于标准库中的模块并查看结果代码的读取方式来检查该决定。在许多使用条件表达式的情况下,一个值似乎是“常见情况”,而一个值是“exceptions情况”,仅在不满足条件的极少数情况下使用。条件语法使此模式更为明显:

内容=((doc +’\ n’)如果文档为其他”)

因此,我认为总体而言,这是一种合理的处理方式,但是您不能凭借以下简单性来参数:

if logging: print data

If you don’t want to from __future__ import print_function you can do the following:

a = 100
b = True
print a if b else "",  # Note the comma!
print "see no new line"

Which prints:

100 see no new line

If you’re not aversed to from __future__ import print_function or are using python 3 or later:

from __future__ import print_function
a = False
b = 100
print(b if a else "", end = "")

Adding the else is the only change you need to make to make your code syntactically correct, you need the else for the conditional expression (the “in line if else blocks”)

The reason I didn’t use None or 0 like others in the thread have used, is because using None/0 would cause the program to print None or print 0 in the cases where b is False.

If you want to read about this topic I’ve included a link to the release notes for the patch that this feature was added to Python.

The ‘pattern’ above is very similar to the pattern shown in PEP 308:

This syntax may seem strange and backwards; why does the condition go in the middle of the expression, and not in the front as in C’s c ? x : y? The decision was checked by applying the new syntax to the modules in the standard library and seeing how the resulting code read. In many cases where a conditional expression is used, one value seems to be the ‘common case’ and one value is an ‘exceptional case’, used only on rarer occasions when the condition isn’t met. The conditional syntax makes this pattern a bit more obvious:

contents = ((doc + ‘\n’) if doc else ”)

So I think overall this is a reasonable way of approching it but you can’t argue with the simplicity of:

if logging: print data

回答 4

从2.5开始,您可以使用C的等价 三元条件运算符,其语法为:

[on_true] if [expression] else [on_false]

所以您的示例很好,但是您只需添加else,例如:

print a if b else ''

Since 2.5 you can use equivalent of C’s ”?:” ternary conditional operator and the syntax is:

[on_true] if [expression] else [on_false]

So your example is fine, but you’ve to simply add else, like:

print a if b else ''

回答 5

您可以使用:

print (1==2 and "only if condition true" or "in case condition is false")

同样,您可以继续以下操作:

print 1==2 and "aa" or ((2==3) and "bb" or "cc")

真实的例子:

>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
1 item found.
>>> count = 2
>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
2 items found.

You can use:

print (1==2 and "only if condition true" or "in case condition is false")

Just as well you can keep going like:

print 1==2 and "aa" or ((2==3) and "bb" or "cc")

Real world example:

>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
1 item found.
>>> count = 2
>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
2 items found.

回答 6

这可以通过字符串格式化来完成。它适用于%表示法以及.format()f字符串(3.6的新功能)

print '%s' % (a if b else "")

要么

print '{}'.format(a if b else "")

要么

print(f'{a if b else ""}')

This can be done with string formatting. It works with the % notation as well as .format() and f-strings (new to 3.6)

print '%s' % (a if b else "")

or

print '{}'.format(a if b else "")

or

print(f'{a if b else ""}')

回答 7

对于您的情况,这可行:

a = b or 0

编辑:这是如何工作的?

在问题中

b = True

所以评估

b or 0

结果是

True

分配给a

如果b == False?b or 0将求值到0将分配给的第二个操作数a

For your case this works:

a = b or 0

Edit: How does this work?

In the question

b = True

So evaluating

b or 0

results in

True

which is assigned to a.

If b == False?, b or 0 would evaluate to the second operand 0 which would be assigned to a.


回答 8

尝试这个 。可能对你有帮助

a=100
b=True

if b:
   print a

Try this . It might help you

a=100
b=True

if b:
   print a

回答 9

您只是太复杂了。

if b:
   print a

You’re simply overcomplicating.

if b:
   print a

回答 10

在以下情况下,您始终需要else内联:

a = 1 if b else 0

但是更简单的方法是a = int(b)

You always need an else in an inline if:

a = 1 if b else 0

But an easier way to do it would be a = int(b).


回答 11

好吧,为什么不简单地写:

if b:
    print a
else:
    print 'b is false'

Well why don’t you simply write:

if b:
    print a
else:
    print 'b is false'

回答 12

嗯,您可以通过列表理解来做到这一点。这只有在您拥有真实范围的情况下才有意义..但是它确实可以做到:

print([a for i in range(0,1) if b])

或仅使用这两个变量:

print([a for a in range(a,a+1) if b])

hmmm, you can do it with a list comprehension. This would only make sense if you had a real range.. but it does do the job:

print([a for i in range(0,1) if b])

or using just those two variables:

print([a for a in range(a,a+1) if b])

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