对于包含列表的循环

时间:2017-11-21 19:11:54

标签: python python-3.x

我需要一些代码的帮助,我无法开始工作, 我必须制作代码以便打印;

Country    Capital
France     Paris 
Uk         London
Belgium    Brussels
etc..

这是我到目前为止所写的内容。

Country = ["France","UK","Belgium","Spain"]
Capital = ["Paris","London","Brussels","Madrid"]
print("\n\t Country \t Capital")
for country in Country:
  print("\t",country)
for capital in Capital:
  print("\t",capital)

但它打印;

 Country     Capital
 France
 UK
 Belgium
 Spain
 Paris
 London
 Brussels
 Madrid

我似乎无法让首都在首都部分之下。请帮助,谢谢

2 个答案:

答案 0 :(得分:4)

这是因为你使用两个单独的循环来打印,所以它们一个接一个地来,你想要一个循环,如下所示:

Country = ["France","UK","Belgium","Spain"]
Capital = ["Paris","London","Brussels","Madrid"]
print("\n\t Country \t Capital")
for i in range(len(Country)):
  print("\t",Country[i], "\t", Capital[i], "\n")

这样,您就会有以制表符分隔的列,而不是所有国家/地区,然后是所有国家/地区。

答案 1 :(得分:3)

你可以用单行代码完成:

print("\n".join("\t".join(t) for t in zip(Country, Capital)))

输出:

France  Paris
UK      London
Belgium Brussels
Spain   Madrid