簡體   English   中英

如何在列中打印嵌套的python列表

[英]How to print a nested python list in columns

我有一個生成python列表的程序,它的輸出是嵌套列表:我希望能夠以列格式打印的列表的列表[名稱,地址,電話號碼]。 似乎在說明問題時這是一個非常簡單的想法,但是我一直無法找到一種簡單的方法來從列表中提取數據。 如果我打印(列表),則列表中的每個項目都會得到類似的內容:['name','address','phone number']等。 我在Windows平台上使用Python 3。 注意:我不是OOP程序員(目前)

關於條例草案

像這樣遍歷列表:

for name,add,num in lis:
   print (name,add,num)

演示:

>>> lis = [['name','address','phone number']]
>>> for name,add,num in lis:
...        print (name,add,num)
...     
name address phone number

您還可以使用字符串格式來獲得更好的外觀輸出:

>>> lis = [['name','address','phone number']]
>>> for name,add,num in lis:
       print ("{:<10}{:^20}{:^10}".format(name,add,num))
...     
name            address        phone number

prettytable可以產生非常漂亮的ASCII表。 教程中的示例

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.align["City name"] = "l" # Left align city names
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])
print x

應該打印這樣的東西

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

使該示例適合您的用例應該很簡單。

for name, address, phone_number in a_list:
    print '{}\t{}\t{}'.format(name, address, phone_number)

您可以使用print語句,例如,如果您希望所有字段都為20個字符寬:

for e in list:
    name, address, phone = e
    print "%20s %20s %20s" % (name, address, phone)

如果給出的其他答案超出字段大小,則會截斷您的記錄。 如果要換行,則需要使用textwrap模塊。

import textwrap
import itertools

col_width = 20

header = ["Name", "Address", "Phone Number"]

def columnar_record(record):
    columns = (textwrap.wrap(item, col_width) for item in record)
    line_tuples = itertools.zip_longest(*columns, fillvalue="")
    lines = ("".join(item.ljust(col_width) for item in line_tuple)
             for line_tuple in line_tuples)
    return "\n".join(lines)

def print_columns(records):
    print(columnar_record(header))
    for record in records:
        print(columnar_record(record))

a = ["Bill Bradley", "123 North Main St., Anytown, NY 12345", "800-867-5309"]
b = ["John Doe", "800 South Main Street, Othertown, CA 95112", "510-555-5555"]

print_columns([a, b])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM