如何使用 if 语句在 while 循环中追加值
How to append values in a while loop by using an if statement
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语句?
这是一个非常简单的问题。如果 if
语句没有 运行,则 g
变量不会递增,因此循环将无限地继续 g
.
的相同值
解决方法是将 g
的增量移到 if 语句之外(但仍在 while 循环中)。这样它会继续过去的值,即使它们不符合 if
条件。
if records[g][1] == second_lowest_score:
names_list.append(records[g][0])
g = g + 1
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语句?
这是一个非常简单的问题。如果 if
语句没有 运行,则 g
变量不会递增,因此循环将无限地继续 g
.
解决方法是将 g
的增量移到 if 语句之外(但仍在 while 循环中)。这样它会继续过去的值,即使它们不符合 if
条件。
if records[g][1] == second_lowest_score:
names_list.append(records[g][0])
g = g + 1