【问题标题】:Python controlling the output "print"Python 控制输出“打印”
【发布时间】:2017-01-01 11:22:04
【问题描述】:
all_path = [[[2, 3, 4, 5], [2, 4, 5], [2, 5]],
            [[2, 3, 4, 5], [2, 4, 5], [2, 5]], 
            [[2, 3, 4, 5], [2, 4, 5], [2, 5]], 
            [[4, 5]],
            [[1, 2, 3, 4, 5], [1, 2, 4, 5], [1, 2, 5]]]
s_dict = {1: {'Origin': '002', 'Destination': '005', 'Cost': '0000.00', 'Stops': '99', 'Time': '00.00'}, 
          2: {'Origin': '002', 'Destination': '005', 'Cost': '0000.00', 'Stops': '11', 'Time': '00.00'}, 
          3: {'Origin': '002', 'Destination': '005', 'Cost': '1450.11', 'Stops': '99', 'Time': '00.00'}, 
          4: {'Origin': '004', 'Destination': '005', 'Cost': '1550.11', 'Stops': '99', 'Time': '22.22'}, 
          5: {'Origin': '001', 'Destination': '005', 'Cost': '0000.00', 'Stops': '99', 'Time': '11.00'}}


for tin in range(1,6):
   print  'From: '+str(int(s_dict[tin]['Origin']))+','+' to: '+str(int((s_dict[tin]['Destination'])))+','+' Stops: '+(s_dict[tin]['Stops'])+','+' Cost: '+(s_dict[tin]['Cost'])+','+' Time: '+(s_dict[tin]['Time']) 
   print  'All routes:'
   for n in range(len(all_path[tin-1])):
       l=''
       for s in range(len(all_path[tin-1][n])):
           l+=   str(all_path[tin-1][n][s])+'->'
       print l

这是输出, 我会引用一部分

从:2,到:5,站点:99,成本:0000.00,时间:00.00

所有路线:

2->3->4->5->

2->4->5->

2->5->

我的问题是多余的'->' 在行尾 我希望它更像

2->3->4->5

有没有办法在最后不显示“额外的”'->'?

【问题讨论】:

    标签: python python-2.7 printing output


    【解决方案1】:

    看看join-方法:

    print '->'.join(str(x) for x in all_path[tin-1][n])
    # print '->'.join(map(str, all_path[tin-1][n]))
    
    > print '->'.join(['1', '2', '3'])  # '->'.join('123')
    1->2->3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2015-01-05
      • 2014-09-06
      相关资源
      最近更新 更多