python - 基于 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 $')
解决方案
您可以使用while
和for
循环:
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))
推荐阅读
- r - 如何在 flexdashboard 中导出 HTML,以便其他没有 R 的人可以看到它?
- r - 如何根据列对齐在 R 中组合文本行
- gradle - 从 Gradle 依赖树中提取依赖细节
- javascript - 单击带有字体真棒图标的按钮时提交表单
- reactjs - 未捕获的类型错误:JSON.parse(...) 为空
- migration - 如何估算迁移到云端所需的时间
- javascript - 如何在单行中将函数包装在函数中以传递参数而不执行它
- list - 尝试将列表“批量转换”为 numpy 数组
- windows - 在 Windows 重新启动时自动启动 Docker
- dart - 飞镖中的异步等待 Future.delayed