Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将此for循环更改为while循环?_Python_Loops_If Statement_While Loop - Fatal编程技术网

Python 如何将此for循环更改为while循环?

Python 如何将此for循环更改为while循环?,python,loops,if-statement,while-loop,Python,Loops,If Statement,While Loop,我有一个代码,当你传入aList=[5,8,2,13,1,8,3,1,8] 它打印countList=[0,2,1,1,0,1,0,0,3,0,0,0,0,1,0,0,0,0,0,0,0]。基本上,假设countList中的索引1是2,因为列表中有两个数字1 这是for循环中的代码: countList = 20*[0] aList = [5,8,2,13,1,8,3,1,8] for num in aList: countList[num] += 1 我尝试将其更改为while循环

我有一个代码,当你传入aList=[5,8,2,13,1,8,3,1,8] 它打印countList=[0,2,1,1,0,1,0,0,3,0,0,0,0,1,0,0,0,0,0,0,0]。基本上,假设countList中的索引1是2,因为列表中有两个数字1

这是for循环中的代码:

countList = 20*[0]

aList = [5,8,2,13,1,8,3,1,8]
for num in aList:
    countList[num] += 1
我尝试将其更改为while循环,但打印countList=[0,2,2,3,0,5,0,0,24,0,0,0,0,0,13,0,0,0,0,0,0,0]

这就是我所尝试的:

countList = 20*[0]

aList = [5,8,2,13,1,8,3,1,8]
index=0#initialize index

while index<len(aList):
    number=aList[index]
    count=0
    while count<number:
        countList[number] += 1
        count+=1
    index+=1
countList=20*[0]
aList=[5,8,2,13,1,8,3,1,8]
索引=0#初始化索引

而指数你有太多的时间。一个for循环可以替换为一个while循环

内部的while是不需要的。将其替换为列表中计数器的增量。 对于一个成功的循环,您只需要跟踪3件事情:遍历元素的索引、初始化和结束条件。 它们在不同的循环命令中位于不同的位置,但逻辑上是相同的

countList = 20*[0]

aList = [5,8,2,13,1,8,3,1,8]
index=0#initialize index

while index<len(aList):
    countList[aList[index]] += 1
    index+=1
countList=20*[0]
aList=[5,8,2,13,1,8,3,1,8]
索引=0#初始化索引

当我不明白时,你可以解释为什么你需要
。为什么要在
时将
切换为
?而您试图解决的真正问题是什么,使用
while
很少是python中惯用的解决方案。我计划将其转换为mips汇编语言,因此我认为while循环会更容易?