Python家庭作业-创建新列表 [英] Python Homework - creating a new list
问题描述
作业:
编写一个名为
splitList(myList, option)
的函数,该函数将一个列表和一个选项(输入值为0或1)作为输入.如果option的值为0,则该函数返回一个列表,该列表由myList中的元素组成,为负数,并且如果该选项的值为1,则该函数返回一个列表,该列表由myList中偶数个元素组成.
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.
我知道如何确定数字是否为偶数以及数字是否为负数.我正在努力寻找如何基于选项"返回新的负数或偶数列表
I know how to determine if a number is even and if a number is negative. I'm struggling with how to return a new list of negative or even numbers based on "option"
这是我到目前为止所得到的:
This is what I've gotten so far:
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标准是四个空格.通常,您可以将编辑器设置为插入四个空格而不是制表符(也不希望将制表符与空格混用).
As I mentioned in my comment, you should standardize your indentation: four spaces is Python standard. You can usually set your editor to insert four spaces instead of tabs (don't want to mix tabs with spaces, either).
关于您的实际问题:尝试编写总共三个函数:一个返回所有负值,一个返回偶数,另一个基于option
调用适当的函数.
As to your actual question: try writing three total functions: one that returns all the negative values, one that returns even values, and one that calls the appropriate function based on 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)
这篇关于Python家庭作业-创建新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!