小能豆

Python 家庭作业 - 创建新列表

py

任务:

编写一个名为的函数splitList(myList, option),该函数以一个列表和一个选项作为输入,该选项为 0 或 1。如果选项的值为 0,则该函数返回一个由 myList 中的负数元素组成的列表;如果选项的值为 1,则该函数返回一个由 myList 中的偶数元素组成的列表。

我知道如何确定一个数字是否为偶数以及一个数字是否为负数。我正在努力弄清楚如何根据“选项”返回一个新的负数或偶数列表

这是我目前得到的:

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)

阅读 17

收藏
2024-12-01

共1个答案

小能豆

The error you’re encountering occurs because you’re defining the function splitList to take only one argument (myList), but you’re trying to pass more than one argument when calling the function. You need to modify your function definition to accept both myList and option as parameters.

Additionally, you’ll need to update your function to check the value of option (whether it’s 0 or 1) and then filter the list accordingly.

Here is the corrected version of your function:

def splitList(myList, option):
    newlist = []

    # If option is 0, filter negative numbers
    if option == 0:
        for i in myList:
            if i < 0:
                newlist.append(i)

    # If option is 1, filter even numbers
    elif option == 1:
        for i in myList:
            if i % 2 == 0:
                newlist.append(i)

    return newlist

Explanation:

  1. Parameters: splitList(myList, option) now accepts two arguments: the list myList and the option option to determine whether to filter negative or even numbers.
  2. Option Check:
  3. If option == 0, it appends negative numbers from myList to newlist.
  4. If option == 1, it appends even numbers from myList to newlist.

Example usage:

my_list = [1, -2, 3, -4, 5, 6]
print(splitList(my_list, 0))  # Output: [-2, -4]
print(splitList(my_list, 1))  # Output: [-2, 6]

This should now work without any errors, and you can pass both the list and the option when calling the function.

2024-12-01