【问题标题】:Formatting output from print on respective lines?在相应的行上格式化打印输出?
【发布时间】:2016-08-31 00:59:57
【问题描述】:

我正在尝试格式化查询结果,以便将结果打印在各自的行上。例如,我正在按商店编号查询商店并从 JSON 文件中获取位置,但是在打印时,商店编号和位置打印在不同的行上:

代码片段:(搜索商店 35 和 96)

for store, data in results.items():
    print('Store: {}'.format(store))
    if data:
        for location in data:
            print(location)

电流输出:
商店:35
{'位置':爱荷华州}
店铺:96
{'位置':明尼苏达州}

期望的输出(或类似的东西):
商店:35,“位置”:爱荷华州
商店:96,“地点”:明尼苏达州

【问题讨论】:

    标签: python python-3.x printing formatting


    【解决方案1】:

    end='' 添加到您的第一个打印语句应该可以解决问题。通过指定结束字符为空字符串,您将覆盖默认的\n 字符(默认情况下打印语句以换行符结尾)。

    for store, data in results.items():
        print('Store: {}'.format(store), end='')
        if data:
            for location in data:
                print(location)
    

    我们只会在第一个打印语句中添加end='',因为我们希望在您打印出位置后打印新行。

    如果您想用, 分隔打印,当然您只需将+ ',' 添加到您的第一个打印语句即可。

    如果您使用的是 Python 3,这将立即生效。如果您使用的是 Python 2.X,则必须将此行添加到文件顶部:from __future__ import print_function

    下面是一个简单的例子:

    from __future__ import print_function
    
    l1 = ['hello1', 'hello2', 'hello3']
    l2 = ['world1', 'world2', 'world3']
    
    for i,j in zip(l1, l2):
        print (i, end='')
        print (j)
    
    Output:
    
    hello1world1
    hello2world2
    hello3world3
    

    如果我们采用相同的代码,但稍作改动并删除end='',就会发生这种情况:

    from __future__ import print_function
    
    l1 = ['hello1', 'hello2', 'hello3']
    l2 = ['world1', 'world2', 'world3']
    
    for i,j in zip(l1, l2):
        print (i)
        print (j)
    
    Output:
    
    hello1
    world1
    hello2
    world2
    hello3
    world3
    

    如您所见,每一行都以换行符结尾,这将为每个语句打印一个新行。

    【讨论】:

    • 您需要在第一个 sn-p 中将else 添加到if data: 以正确处理其值被视为False 的情况。
    • @MiaElla 没问题!如果我能够帮助您,请考虑通过点击检查按钮将其标记为答案!
    【解决方案2】:

    我会将所有输出写入一个变量并在最后只打印一次该变量。这也可以让您节省时间(尽管使用更多内存),因为您只需要一次访问标准输出。代码也更容易理解(在我看来):

    output = ''
    for store, data in results.items():
        output += 'Store: {}'.format(store)
        if data:
            for location in data:
                output += location+'\n'
    
    # Only at the end you print your output
    print(output)
    

    您还可以在每次迭代结束时使用以下命令打印(您仍然有一半的时间访问标准输出):

    for store, data in results.items():
        output = 'Store: {}'.format(store)
        if data:
            for location in data:
                output += location+'\n'
    
        # Print only at the end of the loop
        print(output)
    

    如果您想为每个 Store 换行,但不想为每个“位置”换行:

    output = ''
    for store, data in results.items():
        output += 'Store: {}'.format(store)
        if data:
            for location in data:
                output += location
            output += '\n'
    
    # Only at the end you print your output
    print(output)
    

    我认为这种方法更灵活,更容易在代码中阅读,也更快。

    希望对你有所帮助

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多