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

Python 如何按行打印列表中的元素?,python,list,dictionary,Python,List,Dictionary,这是我的第一个问题。 我有一本这种格式的字典 hostLoc = {'Continent1': list of hosts, 'Continent2': list of hosts ...} 其中主机是类的实例 e、 g 我想打印一些像 Continent1 host1 -TAB- host2 host3 -TAB- host4 Continent2 host1 -TAB- host2 host3 ... 我修改了这样的解决方案 print 'Host Details' for locati

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

hostLoc = {'Continent1': list of hosts, 'Continent2': list of hosts ...}
其中主机是类的实例

e、 g

我想打印一些像

Continent1
host1 -TAB- host2
host3 -TAB- host4
Continent2
host1 -TAB- host2
host3
...
我修改了这样的解决方案

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
打印“主机详细信息”
对于hostLoc.keys()中的位置:
打印'\n',位置
索引=0
对于hostLoc[位置]中的主机:
如果指数<1:
打印主机“\t”,
指数+=1
其他:
打印主机
索引=0

我的问题是,在输出中,一些制表符被“忽略”,一些大陆被两行而不是一行分隔。

如果我理解你所说的,有一种更简单的方法,即使用连接函数。”<代码>\t'。联接(数组)将使用
\t
分隔数组中的所有元素。您可以尝试以下方法:

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

hostLoc()是函数吗,或者为什么要使用
()
。如果它是一个函数,您应该缓存结果,而不是每次都重新调用它。它不是一个函数(错误复制-粘贴)。。。我更正了。谢谢你的回复。我忘了提到主持人是班级。当我尝试您的解决方案时,我得到错误类型错误:序列项0:预期字符串,主机found@user2960286,您的
主机
实例是否在某个地方保存其值?比如
Host.Host
。因此,您必须执行以下操作:
print'\t'.join([host.host for host in hostLoc[location]])+'\n'
我有一个repr方法,该方法返回例如对于主机Pr1Host10:Active Pr1Host10:1.0/1.0,1.0/1.0,10,例如,2,欧洲,如果我执行代码print'\t'.join([host.\u repr\uu(),for host in hostLoc[loc]]))+'\n“我将所有主机放在一行中,在某些情况下不带制表符。我想要的是每行2或3台主机。
for location in hostLoc:    #This gets all of the keys, and is more pythonic than hostLoc.keys()
    print '\t'.join(hostLoc[location])+'\n'