简体   繁体   English

如何打印到同一行-For循环中的If语句

[英]How to print to the same line - If Statement within a For Loop

Python 3 - I am using a for loop to print values from a dictionary. Python 3-我正在使用for循环从字典中打印值。 Some dictionaries within rawData have "RecurringCharges" as an empty list. rawData中的某些词典将“ RecurringCharges”作为一个空列表。 I am checking to see if the list is empty and either populating with "0.0" if empty or the "Amount" if populated. 我正在检查列表是否为空,如果为空,则填充为“ 0.0”,如果为空,则填充为“金额”。

Creating the IF statement in my For Loop presents a new print statement and prints to a new line. 在我的For循环中创建IF语句将显示一个新的打印语句并打印到新行。 I would like it to be one continuous line. 我希望这是一条连续的线。

for each in rawData['ReservedInstancesOfferings']:
    print('PDX', ','
          , each['InstanceType'], ','
          , each['InstanceTenancy'], ','
          , each['ProductDescription'], ','
          , each['OfferingType'], ','
          , each['Duration'], ','
          , each['ReservedInstancesOfferingId'], ','
          , each['FixedPrice'], ',',
          )
    if not each['RecurringCharges']:
        print("0.0")
    else:
        print(each['RecurringCharges'][0].get('Amount'))

如果使用Python 3,请在每个打印语句的末尾添加一个逗号,然后添加end =“”,例如:

 print(each['RecurringCharges'][0].get('Amount'), end="")

I found the answer shortly after posting: include the parameter end='' in the first print statement. 我在发布后不久找到了答案:在第一个打印语句中包含参数end =''。

for each in rawData['ReservedInstancesOfferings']:
    print('PDX', ','
          , each['InstanceType'], ','
          , each['InstanceTenancy'], ','
          , each['ProductDescription'], ','
          , each['OfferingType'], ','
          , each['Duration'], ','
          , each['ReservedInstancesOfferingId'], ','
          , each['FixedPrice'], ',', end=''
          )
    if not each['RecurringCharges']:
        print("0.0")
    else:
        print(each['RecurringCharges'][0].get('Amount'))

Instead of using the print function, use stdout! 不要使用打印功能,而要使用stdout!

import sys
sys.stdout.write('this is on a line ')
sys.stdout.write('and this is on that same line!')

With sys.stdout.write(), if you want a newline, you put \\n in the string, otherwise, it's on the same line. 使用sys.stdout.write(),如果要换行,请将\\ n放在字符串中,否则,它在同一行上。

Of course you could just follow How to print without newline or space? 当然,您可以按照如何在没有换行符或空格的情况下进行打印?

but in that case, it would be better to insert your expression as the last argument in a ternary expression : 但是在那种情况下,最好将您的表达式作为三元表达式中的最后一个参数插入:

      , each['ReservedInstancesOfferingId'], ','
      , each['FixedPrice'], ','
      , "0.0" if not each['RecurringCharges'] else each['RecurringCharges'][0].get('Amount')
      )

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

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