Python 我需要编写相同的程序,但是使用while循环而不是for循环
以下是原始代码:Python 我需要编写相同的程序,但是使用while循环而不是for循环,python,Python,以下是原始代码: def scrollList(myList): negativeIndices = [] for i in range(0,len(myList)): if myList[i] < 0: negativeIndices.append(i) return negativeIndices def滚动列表(myList): 否定条件=[] 对于范围(0,len(myList))中的i: 如果myList[i]
def scrollList(myList):
negativeIndices = []
for i in range(0,len(myList)):
if myList[i] < 0:
negativeIndices.append(i)
return negativeIndices
def滚动列表(myList):
否定条件=[]
对于范围(0,len(myList))中的i:
如果myList[i]<0:
否定条件。附加(i)
返回否定条件
到目前为止,我得到的是:
def scrollList2(myList):
negativeIndices = []
needMoreNumbers = True
while (needMoreNumbers):
if myList[i] < 0:
negativeIndices.append(i)
n = n-1
if (n<1):
needMoreNumbers = False
return negativeIndices
def滚动列表2(myList):
否定条件=[]
needMoreNumbers=True
而(需要更多数字):
如果myList[i]<0:
否定条件。附加(i)
n=n-1
如果(n用一个计数器变量模拟它:
def scrollList2(myList):
negativeIndices = []
counter = 0
while (counter < len(myList)):
if myList[counter] < 0:
negativeIndices.append(counter)
counter += 1
return negativeIndices
def滚动列表2(myList):
否定条件=[]
计数器=0
而(计数器
在i
上出现全局错误的原因是您没有在任何地方定义它。您必须定义您使用的内容。您还没有定义变量n
。在修复i
后,您也会在这方面出现错误
所以,在前面定义n
,而像这样循环
n = len(myList)
while(needsMoreStuff):
并将对i
的引用更改为
if myList[n] < 0:
negativeIndices.append(n)
如果myList[n]<0:
否定条件。附加(n)
应该足以修复您的错误
编辑:
建议使用不同的循环构造,然后对其进行编辑,使其更符合问题。问题是未声明的变量。好的,您可以尝试手动进行索引
def scrollList2(myList):
negativeIndices = []
index = 0
while (index < len(myList)):
if myList[index] < 0:
negativeIndices.append(index)
index+=1
return negativeIndices
def滚动列表2(myList):
否定条件=[]
索引=0
而(索引
蟒蛇式的答案是
indices = [i for i,n in enumerate(mylist) if n<0]
index=[i代表枚举中的i,n(mylist)如果n@Migol很好,我忘记了索引。修复了。你还没有定义I
。而且,计数器
是一种不好的做法,因为这个变量的标准名称是I
或index
。来吧,根据Python的标准,整个代码都是不好的做法!使用while
创建列表?I just想说明我的观点!两个空格缩进对于Python来说是一种糟糕的做法;)更不用说您没有声明i
,而是将它声明为索引,所以myList[i]
和append(i)
会失败吗?看到了吗?每个人都会犯错,我只是没有这么随便地投反对票;)是的,但问题是带着一个while循环。所以我想我们在这一个问题上不会太像python了。@PauloBu嗯,我在解决一个编程问题,而不是一个家庭作业问题。