如何从循环的每个实例收集信息?

2024-04-27 03:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

python非常新,但我想存储每次循环再次运行代码时生成的每个列表,以便在代码的后面部分使用它们

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))
    i = i + 1

3条回答

下面是一种方法:

i = 1
myLists = []

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]

    # append L1 to myLists
    myLists.append(L1)
    print("Line " + str(i) + str(L1))
    i = i + 1

然后,您可以在myLists上循环以使用for循环获取每个生成的列表:

for list in myLists:
    # do smth ...

变量L1将在每次循环迭代时被覆盖。但最后,最后一个值将保留在L1中。如果这是你想要的,那么你已经拥有了

如果要存储所有L1值,请将它们存储在另一个列表中:

lst = []
i = 1
while i <= 5:
  ...
  L1 = [int(units), int(rev), revper, cogs, profit, profitper]
  lst.append(L1)
  ...
print(lst)

当然,对于第三个实例,您可以使用实例lst[2]访问每个迭代

顺便说一下,在编码惯例中,变量不能使用大写字母。这些是为类和常量保留的。因此,最好使用l1而不是L1

希望它对您有所帮助,并帮助您提高python技能;-)

我会使用一组格言:

from pprint import pprint

dict_dict = {}
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 = {
        'Units sold': int(units),
        'Revenue': int(rev),
        'Revenue per unit': revper,
        'Cost of goods sold': cogs,
        'Profit': profit, 
        'Profit per unit': profitper
   }
   dict_dict[i]=L1
   print("Line " + str(i) + str(L1))
   i = i + 1

pprint(dict_dict)

相关问题 更多 >