【问题标题】:How to append values in a while loop by using an if statement如何使用 if 语句在 while 循环中附加值
【发布时间】:2021-06-08 06:00:51
【问题描述】:
records = [["chi", 20.0],["beta", 50.0],["alpha", 50.0]]
a = len(records)
i = 0
b = []
while i < a:
    print(records[i][1])
    b.append(records[i][1])
    i = i + 1
print(b)
c = len(b)
#from previous question
unique_list = []
for el in b:
   if el not in unique_list:
       unique_list.append(el)
   else:
       print ("Element already in the list")
print(unique_list)
second_lowest_score = unique_list[1]
print(second_lowest_score)
names_list = []
g = 0
while g < a:
    if records[g][1] == second_lowest_score:
        names_list.append(records[g][0])
        g = g + 1
print(names_list)

我想要做的是将具有第二低分数 (50) 的记录的名称附加到 names_list。但是,while 循环没有给我任何结果。没有语法错误,所以我不确定我的代码为什么错误。但是,当我使用前面的 while 循环附加数字时,它似乎工作正常。是不是不能在while循环中使用if语句?

【问题讨论】:

    标签: python-3.x list if-statement while-loop append


    【解决方案1】:

    这是一个非常简单的问题。如果if 语句未运行,则g 变量不会递增,因此循环将在g 的相同值上无休止地继续。

    解决此问题的方法是将g 的增量移到 if 语句之外(但仍在 while 循环中)。这样,即使它们不匹配 if 条件,它也会继续过去的值。

    if records[g][1] == second_lowest_score:
        names_list.append(records[g][0])
    g = g + 1
    

    【讨论】:

    • 非常感谢。我得注意这些凹痕。
    猜你喜欢
    • 2015-07-06
    • 2015-05-19
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多