【问题标题】:Converting for loops into while loop [closed]将for循环转换为while循环[关闭]
【发布时间】:2018-10-21 08:22:41
【问题描述】:
for (length, freq) in word_list:
    print(freq_temp.format(length, freq))
print("\n Len  Freq Graph")
for (length, freq) in word_list:
    graph_template = "{:>4}{:>5}% {}"
    number_symbol = "=" * percentage_frequency(freq, new_list)
    print(graph_template.format(length, percentage_frequency(freq, new_list),number_symbol))

如何将这些 for 循环转换为 while 循环?

【问题讨论】:

  • 为什么要把它转换成while循环?您在使用 for 循环时遇到了什么问题?
  • 什么是while 循环与for 循环的比较?
  • 我只是好奇你会怎么做。我已经完成了其他转换,但这一次让我很困惑。

标签: python


【解决方案1】:

您错过了forwhile 循环的要点,this question does a good job of explaining it

基本上,for 循环遍历列表,您可以像这样做一样对项目进行操作。

相比之下,while 循环用于运行直到满足条件,例如触发标志。

for 循环:

mylist = ["this", "is", "a", "for", "loop"]
for element in mylist:
    print(element)

返回:

this
is
a
while
loop

这个while循环在哪里:

count = 0
while count != 10:
    print(count)
    count += 1
print("count has reached 10")

返回:

0
1
2
3
4
5
6
7
8
9
count has reached 10

总而言之,for 循环用于遍历arraygenerator 对象,而while 循环用于运行直到满足条件。

【讨论】:

    猜你喜欢
    • 2016-07-01
    • 2018-02-22
    • 2017-04-26
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    相关资源
    最近更新 更多