python - 将for循环转换为python中的while循环

标签 python loops for-loop while-loop iteration

我正在努力寻找一种有效的方法将这些 for 循环转换为一组有效的 while 循环。有什么建议么?我正在使用 2.7

def printTTriangle(height):
 for row in range(1,height+1):
    # print row T's
    for col in range(1,row+1):
        print 'T', 
    print

谢谢大家的帮助!

最佳答案

是这样的:

def printTTriangle(height):
    row = 1
    while row < height+1:
        col = 1
        while col < row+1:
            print 'T', 
            col += 1
        print
        row += 1

这是我的做法。例如,让我们转换这一行:

for row in range(1, height+1):

第一步:创建迭代变量并初始化为范围的起始值:

row = 1

第二步:将范围的结束值转换为循环条件,注意索引:

while row < height+1:

最后,不要忘记推进递增迭代变量的循环:

row += 1

综合起来:

row = 1
while row < height+1:
    row += 1

关于python - 将for循环转换为python中的while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18900624/

相关文章:

python - 从 TfidfVectorizer 获取全文

python - Pandas 映射到下周的星期一

python - 为什么Python的reduce在对列表列表求和时会引发类型错误?

python - Python中的错误处理可以检测程序状态

php - 在轮播容器中循环 3 篇 WordPress 文章

Python JSON try except block 不起作用

javascript - 如何用JS复制字符串中的每个字母

python - 字母表中的下一个字母

javascript - "array.length -1"在 JavaScript 中是什么意思?

C# 为什么 Array.IndexOf 返回 -1