python创建列表的方法解决问题,Python家庭作业-创建新列表

分配:

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 "", line 1, in

builtins.TypeError: splitList() takes exactly 1 positional argument (4 given)

解决方法:

正如我在评论中提到的那样,您应该对缩进进行标准化:四个空格是Python标准.通常,您可以将编辑器设置为插入四个空格而不是制表符(也不希望将制表符与空格混合使用).

关于您的实际问题:请尝试编写总共三个函数:一个返回所有负值,一个返回偶数,另一个基于选项调用适当的函数.

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,list

来源: https://codeday.me/bug/20191011/1895150.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值