Converting a for loop to a while loop

前端 未结 5 1008
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 03:19

I am new to Python and I need to convert a for loop to a while loop and I am not sure how to do it. This is what I am working with:



        
相关标签:
5条回答
  • 2020-12-12 04:05

    The problem here is not that you need a while loop, but that you should use python for loops properly. The for loop causes iteration of a collection, in the case of your code, a sequence of integers.

    for n, val in enumerate(mylist):
        if val < 0: negativeindices.append(n)
    

    enumerate is a builtin which generates a sequence of pairs of the form (index, value).

    You might even perform this in a functional style with:

    [n for n, val in enumerate(mylist) if val < 0]
    

    This is the more usual python idiom for this sort of task. It has the advantage that you don't even need to create an explicit function, so this logic can remain inline.

    If you insist on doing this with a while loop, here's one that take advantage of python's iteration facilities (you'll note that it's essentially a manual version of the above, but hey, that's always going to be the case, because this is what a for loop is for).:

    data = enumerate(list)
    try:
        while True:
            n, val = next(data)
            if val < 0: negativeindices.append(n)
    except StopIteration:
        return negativeindices
    
    0 讨论(0)
  • 2020-12-12 04:07
    def scrollList(myList):
          negativeIndices = []
          while myList:
              num = myList.pop()
              if num < 0:
                 negativeIndices.append(num)
          return negativeIndices
    
    0 讨论(0)
  • 2020-12-12 04:08

    Just setup a variable for the loop and increment it.

    int i = 0;
    while(i<len(myList)):
        if myList[i] < 0:
            negativeIndices.append(i)
        i++;
    
    return negativeIndices
    
    0 讨论(0)
  • 2020-12-12 04:13

    like this:

    def scrollList(myList):
          negativeIndices = []
          i = 0
          while i < len(myList):
                if myList[i] < 0:
                     negativeIndices.append(i)
                i += 1
          return negativeIndices
    
    0 讨论(0)
  • 2020-12-12 04:14

    The first answer is the straightforward way, there is another way, if you're allergic to incrementing your index variables:

    def scrollList(myList):
      negativeIndices = []
      indices = range(0,len(myList)):
      while indices:
            i = indices.pop();
            if myList[i] < 0:
                 negativeIndices.append(i)
      return negativeIndices
    
    0 讨论(0)
提交回复
热议问题