繁体   English   中英

关于while循环的问题。 我的代码有什么问题?

[英]Question on while loop. What's wrong with my code?

这个问题需要我构建一个 while 循环来显示存储在列表 PlayListRatings 中的专辑播放列表的评分值,假设分数小于 6,并且列表 PlayListRatings 由以下公式给出: PlayListRatings = [10, 9.5, 10, 8、7.5、5、10、10]。

我的代码是


PlayListRatings= [10,9.5,10,8,7.5,5,10,10]

NewPlayListRatings=[]


while(PlayListRatings[i]> 6):

    NewPlayListRatings.append(PlayListRatings[i])

    i=i+1
    

output 为 [10, 9.5, 10, 8, 7.5]

但建议的答案表明了这一点:

PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
i = 0
Rating = PlayListRatings[0]
while(i < len(PlayListRatings) and Rating >= 6):
    Rating = PlayListRatings[i]
    print(Rating)
    i = i + 1

output 与我的略有不同。

[10 9.5 8 7.5 5]

包括5个。

有人可以告诉我我的代码有什么问题吗? 谢谢你。

首先,考虑到您在 while 循环声明中使用i之前没有定义它,我不确定您是如何设法从您的代码中获得 output 的。

在引用一个值之前,在这种情况下i ,您必须首先声明该值。 这就是第二行接受的答案: i = 0

现在,您的循环条件是while(PlayListRatings[i]> 6)如果您要将其翻译成英文,它会说“只要PlayListRatings[i]大于6就循环。当循环达到值5时,您的循环条件变成了while(5 > 6) ,因为不是,所以循环里面的代码没有被执行,然后循环终止。这就是为什么 5 不在最终列表中的原因。

首先它的发生是因为您在打印之前更改了 Rating 变量,并且在第二个循环中检查了它之后,您想得太难了! 这就像 C 语言代码!

PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
[print(x) for x in PlayListRatings if x> 6]

或者如果你想保存列表

PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
new_list = [x for x in PlayListRatings if x> 6]
print(new_list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM