如何在行中打印列表的元素?

时间:2013-11-21 20:30:41

标签: python list dictionary

这是我的第一个问题。 我有这种格式的字典

hostLoc = {'Continent1': list of hosts, 'Continent2': list of hosts ...}

其中host是类的实例

e.g。

hostLoc = {'Europe': [Active Pr1Host10: 1.0/1.0 , 1.0/1.0 , 10 , E , 2 , Europe , 1], 'Australia': [Active Pr1Host02: 1.0/1.0 , 1.0/1.0 , 10 , E , 1 , Australia , 1, Active Pr1Host05: 1.0/1.0 , 1.0/1.0 , 10 , E , 1 , Australia , 1, Active Pr1Host13: 1.0/1.0 , 1.0/1.0 , 10 , E , 3 , Australia , 1].....}

我想打印类似

的内容
Continent1
host1 -TAB- host2
host3 -TAB- host4
Continent2
host1 -TAB- host2
host3
...

我像这样修改了this解决方案

print 'Host Details'
for location in hostLoc.keys():
    print '\n', location
    index = 0
    for host in hostLoc[location]:
        if index < 1:
                print host, '\t',
                index += 1
        else:
                print host
                index = 0

我的问题是,在输出中,某些标签被“忽略”,而某些大陆则被两行而不是一行隔开。

1 个答案:

答案 0 :(得分:0)

如果我理解你在说什么,有一个更简单的方法,即使用连接功能。 '\t'.join(array)会将数组中的所有元素与\t分开。你可以尝试这样的事情:

for location in hostLoc:    #This gets all of the keys, and is more pythonic than hostLoc.keys()
    print '\t'.join(hostLoc[location])+'\n'