首页 > 解决方案 > 从列表中以表格格式排列数据

问题描述

我有一个如下列表,并希望将其显示在 5 列中,一列一列

lsit = ['Alexander City', 'Andalusia', 'Anniston', 'Athens', 'Atmore', 
        'Auburn', 'Bessemer', 'Birmingham', 'Chickasaw', 'Clanton', 
        'Cullman', 'Decatur', 'Demopolis', 'Dothan', 'Enterprise', 
        'Eufaula', 'Florence', 'Fort Payne', 'Gadsden', 'Greenville',
        'Guntersville', 'Huntsville']

尝试过,print("\t".join(lsit))但数据未正确填充

>>> print("\t".join(lsit))
Alexander City  Andalusia   Anniston    Athens  Atmore  Auburn  Bessemer    Birmingham  Chickasaw   Clanton Cullman DecaturDemopolis    Dothan  Enterprise  Eufaula Florence    Fort Payne  Gadsden Greenville  Guntersville    Huntsville

有人可以指导如何在 python 中实现这一点吗?

标签: pythonpython-3.x

解决方案


那么你所缺少的就是以五个一组的方式打印它们:

for i in range(0, len(lsit), 5):
    print("\t".join(lsit[i: i+5]))

这使:

Alexander City  Andalusia   Anniston    Athens  Atmore
Auburn  Bessemer    Birmingham  Chickasaw   Clanton
Cullman Decatur Demopolis   Dothan  Enterprise
Eufaula Florence    Fort Payne  Gadsden Greenville
Guntersville    Huntsville

推荐阅读