python - 列表未在 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:]
解决方案
对您的代码的评论:
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
你应该做什么:
- 在循环中:
- 测试最终循环是否为空 = 第一次运行
- 如果第一次运行将所有结果添加到最终列表
- 否则只添加你的第二个结果
推荐阅读
- amazon-web-services - 如何为 aws EKS 上的 nodePort 添加规则以允许某些端口范围内的流量?
- react-native - 带有 onLongPress 回调的 FlatList
- api - 我怎样才能接受人类口音(Wavenet 或 Ssml 声音)?
- python - 饼状图上的参数 Matplotlib、百分比大小、颜色
- angular - 如果地址字段为空,如何将地址添加为不适用。否则显示为地址
- haskell - 过滤代数数据类型列表
- sql - 用于打印 n 行的 SQL 查询
- debian - Opam init - 求解器失败(Debian)
- python - 在单元级别设置操作
- css - 嵌套网格 MUI 反应