【问题标题】:List not resetting in for loop列表未在 for 循环中重置
【发布时间】:2021-12-22 03:58:13
【问题描述】:

我是初级程序员。我正在尝试运行一个循环并获取一个列表。该代码将根据用户输入运行不同的方程(函数)并编译一个列表。我想运行循环并为第一个循环获取列表中的所有值,并为循环的后续运行获取第二个值,并将它们添加到最终列表中。但是,在每个循环之后, 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:]

【问题讨论】:

  • 您应该添加所有变量以重现您的代码和预期的输出;)
  • 你可能想在循环外定义dummy_list = [],在循环内定义append

标签: python list loops slice add


【解决方案1】:

对您的代码的评论:

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

你应该做什么:

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

【讨论】:

  • 但是,如果 'for' 和 'dummy_list' 在同一个缩进上,代码将无法运行。
  • 抱歉,只是格式问题(我已更正)。只是让您看看发生了什么以及为什么可能没有预期的结果。
  • 注意dummy_list = (result[0])替换result[0]的空列表绑定,它不会被添加到原来的空列表中。
猜你喜欢
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多