首页 > 解决方案 > 列表未在 for 循环中重置

问题描述

我是初级程序员。我正在尝试运行一个循环并获取一个列表。该代码将根据用户输入运行不同的方程(函数)并编译一个列表。我想运行循环并为第一个循环获取列表中的所有值,并为循环的后续运行获取第二个值,并将它们添加到最终列表中。但是,在每个循环之后, dummy_list 不会重置,我无法获得该特定循环的唯一列表。它只是添加。我很难指定从第一个循环中检索列表中的所有值并省略第一个值并在后续循环中检索剩余值。

for i in range (cycles):
    dummy_list = []
    a = input("type choice: " )
    b = int(input("angle: " ))
    c = int(input("exponent: " ))
    result = equation1 (a , b , c)
    dummy_list = (result[0])

final_list += dummylist[1:]

标签: pythonlistloopssliceadd

解决方案


对您的代码的评论:

for i in range (cycles):
    dummy_list = [] # here you create an empty list
    a = input("type choice: " )
    b = int(input("angle: " ))
    c = int(input("exponent: " ))
    result = equation1 (a , b , c)
    dummy_list = (result[0]) # add one item to empty list
    # at this point dummy_list always has only one element 

final_list += dummylist[1:] # get 2nd and next elements of a one element list

你应该做什么:

  • 在循环中:
    • 测试最终循环是否为空 = 第一次运行
    • 如果第一次运行将所有结果添加到最终列表
    • 否则只添加你的第二个结果

推荐阅读