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循环捕获的情况下使它工作。
任何想法或提示都将不胜感激,谢谢!
答案 0 :(得分:1)
尝试以下方法:
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)
答案 1 :(得分:1)
由于没有严格遵守你的问题而有可能吸引downvotes,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))
输出:
[1, 2, 3, 4, 5, 6]
[-10]
>>>
理解中条件的语法看起来很复杂,因为option
到效果的映射很差。在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]
>>>
请注意,这是多么灵活:将代码调整为完全不同的过滤条件变得微不足道。
答案 2 :(得分:0)
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)
答案 3 :(得分:0)
def splitList(myList, option):
snappyList = []
while len(myList) > 0:
i = myList.pop()
if option == 0:
if i > 0:
snappyList.append(i)
if option == 1:
if i < 0:
snappyList.append(i)
return snappyList
答案 4 :(得分:0)
def splitList(myList, option):
snappyList = []
myList_iter = iter(myList)
sentinel = object()
while True:
i = next(myList_iter, sentinel)
if i == sentinel:
break
if option == 0:
if i > 0:
snappyList.append(i)
if option == 1:
if i < 0:
snappyList.append(i)
return (snappyList)
或者,您可以使用异常处理程序而不是sentinel
def splitList(myList, option):
snappyList = []
myList_iter = iter(myList)
while True:
try:
i = next(myList_iter)
except StopIteration:
break
if option == 0:
if i > 0:
snappyList.append(i)
if option == 1:
if i < 0:
snappyList.append(i)
return (snappyList)
答案 5 :(得分:0)
这是一种实际拆分列表的简洁方法,而不仅仅是过滤它:
from operator import ge,lt
def splitlist(input, test=ge, pivot=0):
left = []
right = []
for target, val in (((left if test(n, pivot) else right), n) for n in input):
target.append(val)
return left, right
你会注意到它使用for循环,因为它是正确的做事方式。