使用Python和tabulate库根据用户输入动态调整表格行列的实现问题
实现代码
#!/bin/python3 from tabulate import tabulate # 批量输入,默认空格分隔,可自行修改split参数指定分隔符 uids = input('Enter all UIDs (separated by space) $ ').split() names = input('Enter all names (separated by space) $ ').split() numbers = input('Enter all numbers (separated by space) $ ').split() # 校验三个字段输入数量一致 if not (len(uids) == len(names) == len(numbers)): raise ValueError("UID、姓名、号码的输入数量不匹配,请检查后重新输入") headers = ["UID", "NAME", "NUMBER"] # 打包为tabulate要求的二维表格结构 table = list(zip(uids, names, numbers)) # 输出表格 print(tabulate(table, headers, tablefmt="fancy_grid"))
说明
- 分隔符自定义:如果你的姓名包含空格,可以将
.split()改为.split(',')指定逗号为分隔符,输入时对应使用逗号分隔内容即可 - 类型注意:不要将号码输入转为int类型,避免号码中带横杠、前缀0等特殊字符时报错
- 兼容性:输入多少行数据就会生成对应行数的表格,不需要提前写死变量数量
使用示例
输入内容:
Enter all UIDs (separated by space) $ 0 1 2 Enter all names (separated by space) $ JAMES ANDREW SHAWN Enter all numbers (separated by space) $ 444-5555 666-3333 444-3333
运行后即可输出你示例中的3行表格。
内容的提问来源于stack exchange,提问作者WaXxX333
相关产品推荐
相关产品推荐

