首页 > 解决方案 > 基于 Python 的用户输入在表中添加或减去列/行

问题描述

我正在编辑这篇文章,因为我没有很好地解释我的问题,所以又来了。我正在使用制表库。我希望input()根据给定的输入自动调整表中的列/行数。这是一个基本示例:

#!/bin/python3
from tabulate import tabulate
uid1 = input('UID > ')
uid2 = input('UID > ')
name1 = input('NAME > ')
name2 = input('NAME > ')
number1 = input('NUMBER > ')
number2 = input('NUMBER > ')
headers = ["UID", "NAME","NUMBER"]
table = [[uid1,name1,number1],[uid2,name2,number2]]
print(tabulate(table, headers, tablefmt="fancy_grid"))
╒═══════╤═════════╤══════════╕
│   UID │ NAME    │ NUMBER   │
╞═══════╪═════════╪══════════╡
│     0 │ SHAWN   │ 333-4444 │
├───────┼─────────┼──────────┤
│     1 │ MICHAEL │ 222-3333 │
╘═══════╧═════════╧══════════╛

但是下次脚本运行时,会有更多的列/表:

╒═══════╤════════╤══════════╕
│   UID │ NAME   │ NUMBER   │
╞═══════╪════════╪══════════╡
│     0 │ JAMES  │ 444-5555 │
├───────┼────────┼──────────┤
│     1 │ ANDREW │ 666-3333 │
├───────┼────────┼──────────┤
│     2 │ SHAWN  │ 444-3333 │
╘═══════╧════════╧══════════╛

所以我试图想办法用for循环或其他东西调整行和列的给定值,但我想不通。我想要类似的东西:

UIDs = input('Enter all UIDs $ ')
NAMES = input('Enter all names $ ')
NUMBERS = int(input('Enter all numbers $')

标签: pythonvariablesstring-formattingtabulate

解决方案


您可以使用whilefor循环:

def get_headers():
    print('--HEADERS--')
    headers = []
    while True:
        new_h = input('New header value: ')
        # Break if no value given
        if new_h == '':
            break
        headers.append(new_h)

    return headers


def get_body(head_len):
    print('--BODY--')
    body = []
    while True:
        # Check if user will add new values to make new row
        print('--New Row--')
        new_col = input('New value: ')
        # Break if no value given
        if new_col == '':
            break
        # Each sub array is a row
        body.append([])
        # Append previous test value
        body[-1].append(new_col)
        # -1 because we alreade added the 1st value
        for column in range(head_len-1):
            new_col = input('New value: ')
            # This will append the new value to the last array added
            body[-1].append(new_col)
   
    return body

headers = get_headers()

# Here the lenght of the headers array is provided, so that the
# body rows are the same
body = get_body(len(headers))

推荐阅读