作业:
Write a function called
splitList(myList, option)that takes, as input, a list and an option, which is either 0 or 1. If the value of the option is 0, the function returns a list consisting of the elements in myList that are negative, and if the value of the option is 1, the function returns a list consisting of the elements in myList that are even.
我知道如何判断一个数是偶数还是负数。我正在努力研究如何根据“选项”返回一个新的负数或偶数列表
这是我到目前为止得到的:
def splitList(myList):
newlist = []
for i in range(len(myList)):
if (myList[i]%2 == 0):
newlist.append(myList [i])
return newlist
这个程序报错如下:
Traceback (most recent call last): File "<string>", line 1, in <fragment>
builtins.TypeError: splitList() takes exactly 1 positional argument (4 given)
请您参考如下方法:
正如我在评论中提到的,您应该标准化缩进:四个空格是 Python 标准。您通常可以将编辑器设置为插入四个空格而不是制表符(也不想将制表符与空格混合)。
关于您的实际问题:尝试编写总共三个函数:一个返回所有负值,一个返回偶数,一个根据 option 调用适当的函数。
def splitlist(myList, option):
if option == 1:
return get_even_elements(myList)
elif option == 0:
return get_negative_elements(myList)
def get_even_elements(myList):
pass # Implementation this method here.
def get_negative_elements(myList):
pass # Implementation this method here.
# Test it out!
alist = [-1, 2, -8, 5]
print splitlist(alist, 0)
print splitlist(alist, 1)
