如何将这个for循环变成while循环python

2024-10-03 21:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Converting a for loop to a while loop

def splitList(myList, option):
    snappyList = []
    for i in myList:
        if option == 0:
            if i > 0:
                snappyList.append(i)
        if option == 1:
            if i < 0:
                snappyList.append(i)
    return (snappyList)

嗨,我有这段代码,在for循环下很好用。它根据用户输入的内容返回正或负元素。我需要让它在while循环下工作,我不知道如何让它在while循环中工作。在

如有任何建议或建议,将不胜感激,谢谢!在


Tags: toloopforifdef建议optionappend
3条回答

尝试以下操作:

def splitList(myList, option):
    snappyList = []
    i = 0
    while i < len(myList):
        if option == 0:
            if myList[i] > 0:
                snappyList.append(myList[i])
        if option == 1:
            if myList[i] < 0:
                snappyList.append(myList[i])
        i+=1
    return (snappyList)

Python由于没有严格遵守您的问题而冒着被否决的风险,与许多其他更传统的语言相比,Python具有更好的(简单)循环功能。(我也意识到,根据今早有非常相似的问题,这可能是家庭作业)。显然,了解while循环是如何工作的有一定价值的,但是在Python中这样做会使其他功能变得模糊。例如,使用单一列表理解的示例:

def splitList2(myList, option):
    return [v for v in myList if (1-2*option)*v > 0]

print(splitList2([1,2,3,-10,4,5,6], 0))
print(splitList2([1,2,3,-10,4,5,6], 1))

输出:

^{pr2}$

理解中条件的语法看起来很复杂,因为option到effect的映射很差。在Python中,与许多其他动态和函数式语言一样,可以直接传入比较函数:

def splitList3(myList, condition):
    return [v for v in myList if condition(v)]

print(splitList3([1,2,3,-10,4,5,6], lambda v: v>0))
print(splitList3([1,2,3,-10,4,5,6], lambda v: v<0))
print(splitList3([1,2,3,-10,4,5,6], lambda v: v%2==0))

[1, 2, 3, 4, 5, 6]
[-10]
[2, -10, 4, 6]
>>>     

请注意这是多么灵活:将代码调整为完全不同的过滤条件变得很简单。在

def splitList(myList, option):
    snappyList = []
    myListCpy=list(myList[:]) #copy the list, in case the caller cares about it being changed, and convert it to a list (in case it was a tuple or similar)
    while myListCpy:  #There's at least one element in the list.
        i=myListCpy.pop(0)  #Remove the first element, the rest continues as before.
        if option == 0:
            if i > 0:
                snappyList.append(i)
        if option == 1:
            if i < 0:
                snappyList.append(i)
    return (snappyList)

相关问题 更多 >