Python如何收集循环每次迭代的信息并存储生成的列表供后续使用
实现方法
- 第一步:在while循环开始前,初始化一个空列表,比如命名为
saved_records,用来存储每次循环生成的L1列表 - 第二步:在每次循环生成L1之后,调用
append()方法把L1添加到saved_records里 - 循环结束后,所有运行生成的列表都会按顺序保存在
saved_records中,后续代码直接调用这个变量即可
修改后的完整代码如下:
# 初始化空列表存储所有循环生成的数据 saved_records = [] i = 1 while i <= 5: units = input("Insert Units Sold: ") rev = input("Insert Revenue of Sale: ") revper = round((int(rev) / int(units))) print("Revenue per unit: " + str(revper)) cogs = (3 * int(units)) print("Cost of Goods Sold: " + str(cogs)) profit = (int(rev) - (cogs)) print("Profit: " + str(profit)) profitper = round((profit / int(units))) print("Profit per Unit: " + str(profitper)) L1 = [int(units), int(rev), revper, cogs, profit, profitper] print("Line " + str(i) + str(L1)) # 把当前次生成的列表添加到总存储列表中 saved_records.append(L1) i = i + 1 # 后续使用示例: # 打印所有存储的记录 print("所有循环生成的数据:", saved_records) # 取第2次循环生成的数据(Python下标从0开始,所以第2次对应索引1) print("第2次循环的数据:", saved_records[1])
如果后续读取数据不想记每个字段对应的下标位置,也可以把每次生成的数据改成字典格式,直接通过字段名取值更方便,替换L1的定义即可:
L1 = { "units_sold": int(units), "revenue": int(rev), "revenue_per_unit": revper, "cogs": cogs, "profit": profit, "profit_per_unit": profitper }
内容的提问来源于stack exchange,提问作者Charles Carew-Reid
相关产品推荐
相关产品推荐

