将Python输出打印为两列

时间:2020-02-15 00:07:28

标签: python

尝试在Python程序中复制基本列命令以通过命令行向用户打印状态列表:

us_states_list_with_population = [   
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
...

]

for state_name , state_abbreviation , num_counties in us_states_list_with_population: 
    print(state_name + " (" + state_abbreviation + ")")

是否有一种简单的方法可以将输出分为两列或三列,以使其更短,更易读?

所需的输出将类似于:

Alabama (AL)        Alaska (AK)
Montana (MT)        California (CA)
...

对:

Alabama (AL)
Alaska (AK)
Montana (MT)
California (CA)
...

2 个答案:

答案 0 :(得分:1)

要获得所需的输出,可以尝试一下。

us_states_list_with_population = [   
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
]

row = []
num_of_columns = 2
for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    row.append(f'{state_name} ({state_abbreviation})')
    if len(row) == num_of_columns:
        print(("\t").join(row))
        row.clear()
print(("\t").join(row)) # print last row if there is a remainder

或者,如果您想了解更多信息,请查看@ cricket_007注释。

答案 1 :(得分:0)

您可以通过制表符(而不是空格)将它们分开。

for state_name , state_abbreviation , num_counties in us_states_list_with_population: 
    print(state_name + "\t(" + state_abbreviation + ")")

其中的\t在打印时将转换为标签。