将for循环转换为while循环

时间:2018-10-21 08:22:42

标签: python

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循环?

1 个答案:

答案 0 :(得分:0)

您错过了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循环用于运行直到满足条件