简体   繁体   English

如何在python 2.7中使用内联if else语句单行打印

[英]how to print in single line with an inline if else statement in python 2.7

I am using python2.7. 我正在使用python2.7。 The below code works if I remove , in the print statement. 如果我在print语句中删除了,下面的代码将起作用。 but that prints the values in different lines. 但这会将值打印在不同的行中。 I want to print in same line with an inline if-statement if possible. 如果可能的if-statement我希望在同一行中使用内联if-statement进行打印。

Here is what I have: 这是我所拥有的:

def binary(x):

   for i in [128,64,32,16,8,4,2,1]:
      #if x&i: print 1,
      #else: print 0,
       print 1, if x&i else 0

binary(127)

It throws the following syntax error: 它引发以下语法错误:

File "binary.py", line 6
    print 1, if x&i else 0
              ^
SyntaxError: invalid syntax
def binary(x):
   for i in [128,64,32,16,8,4,2,1]:
       print 1 if x&i else 0,

binary(127)

Put the comma at the end : 将逗号放在末尾

print 1 if x&i else 0,

You are using a conditional expression, of the form true_expr if condition_expr else false_expr , and the part before the if ( true_expr ) is part of that expression. 您正在使用条件表达式,其形式为true_expr if condition_expr else false_expr ,而iftrue_expr之前的部分是该表达式的一部分。 you are printing the outcome of that expression. 您正在打印该表达式的结果。

As the other answers have stated, putting the comma at the end of the print line will solve your problem. 正如其他答案所指出的那样,将逗号放在print行的末尾将解决您的问题。

However, there is a far easier way to achieve what you want if you use format : 但是,如果使用format ,则有一种更简单的方法来实现所需的功能:

>>> def binary(x):
...     return " ".join(format(n, "08b"))
...
>>> print binary(127)
0 1 1 1 1 1 1 1
>>>

This method does the same thing as your function, only it is a lot more concise and efficient. 此方法与您的功能具有相同的作用,只是更加简洁高效。

x = 127

>>> [1 if ele & x else 0 for ele in [128, 64, 32, 16, 8, 4, 2, 1]]
[0, 1, 1, 1, 1, 1, 1, 1]

You can even use, 您甚至可以使用

x = 127

>>> [[0,1][bool(ele & x)] for ele in [128, 64, 32, 16, 8, 4, 2, 1]]
[0, 1, 1, 1, 1, 1, 1, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM