gpt4 book ai didi

Python:动态地将用户定义的数据插入到二维列表中

转载 作者:行者123 更新时间:2023-12-01 08:27:11 29 4
gpt4 key购买 nike

我正在尝试创建一个供应商每周销售额的表格,如下所示:

Monday    Tuesday    Wednesday    
50 80 10
54 98 7
29 40 80

我试图让用户插入每日销售额,这是我到目前为止所得到的:

weekly_sales_list = [['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', []]]

for i in range(len(weekly_sales_list)):
for j in range(len(weekly_sales_list[i])):
weekly_sales_list[i][j] = input('input value for ' + weekly_sales_list[i][j])
print(weekly_sales_list)

我不确定这是否是设置二维列表的最佳方法,并且我还收到以下错误:

TypeError: can only concatenate str (not "list") to str

如有任何帮助,我们将不胜感激

最佳答案

使用字典,以星期名称为键,以该星期的数据为值。

import itertools
data = {'Monday':[],
'Tuesday':[],
'Wednesday':[],
'Thursday':[],
'Friday':[],
'Saturday':[],
'Sunday':[]}
while 1:
info = input('Enter day and value (e.g. "Monday 26") or nothing to stop: ')
if not info:
break
k,v = info.split()
data[k].append(v)

然后通过显示标题来打印表格:

print(*(f'{day:<10}' for day in data))

最后,使用 itertools.zip_longest 转置数据,处理值比其他日期少的日期:

for group in itertools.zip_longest(*data.values(), fillvalue=''):
print(*(f'{value:<10}' for value in group))

示例输入:

Enter day and value (e.g. "Monday 26") or nothing to stop: Monday 3
Enter day and value (e.g. "Monday 26") or nothing to stop: Monday 4
Enter day and value (e.g. "Monday 26") or nothing to stop: Monday 5
Enter day and value (e.g. "Monday 26") or nothing to stop: Tuesday 6
Enter day and value (e.g. "Monday 26") or nothing to stop: Tuesday 7
Enter day and value (e.g. "Monday 26") or nothing to stop: Wednesday 8
Enter day and value (e.g. "Monday 26") or nothing to stop: Thursday 9
Enter day and value (e.g. "Monday 26") or nothing to stop:

结果示例:

Monday     Tuesday    Wednesday  Thursday   Friday     Saturday   Sunday
3 6 8 9
4 7
5

关于Python:动态地将用户定义的数据插入到二维列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54166244/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com