能被2整除:Python

0 投票
5 回答
8990 浏览
提问于 2025-04-17 18:26

我正在尝试写一个叫做 splitList(myList, option) 的函数,这个函数需要两个参数,一个是列表 myList,另一个是选项 option,这个选项只能是 01。如果选项的值是 0,那么这个函数就会返回一个新列表,这个列表里包含了 myList 中所有的负数;如果选项的值是 1,那么函数就会返回一个新列表,这个列表里包含了 myList 中所有的偶数(我们认为0是偶数,因为它能被2整除)。

举个例子:

splitList([1,-3,5,7,-9,-11,0,2,-4], 0)

这个例子会返回这样的列表:

[-3,-9,-11,-4]

而:

splitList([1,-3,5,7,-9,-11,0,2,-4], 1)

这个例子会返回这样的列表:

[0,2,-4]

在这个问题中,我必须使用一个 for loop(循环)。

这是我目前写的代码:

def splitList(myList, option):
    negativeValues = []
    positiveValues = []
    evenValues = [] 
    for i in range(0,len(myList)):       
        if myList[i] < 0: 
            negativeValues.append(myList [i]) 
        else: 
            positiveValues.append(myList [i]) 

    for element in myList: 
        if option == 1: 
            myList [i] % 2 == 0 
            evenValues.append(myList [i]) 
            return evenValues 
        else: 
            return negativeValues

我唯一做不到的就是对列表进行排序,并返回所有能被2整除的数字。

5 个回答

2

你可以用这些基本的东西来构建你所有的变体:

def even_list(numbers):
    return [x for x in numbers if not (x & 1)]

def odd_list(numbers):
    return [x for x in numbers if x & 1]

def negative_list(numbers):
    return [x for x in numbers if x < 0]

def positive_list(numbers):
    return [x for x in numbers if x > 0]

然后进行测试:

>>> def test():
...     numbers = list(range(-3, 4))
...     print even_list(numbers)
...     print odd_list(numbers)
...     print positive_list(numbers)
...     print negative_list(numbers)
... 
>>> test()
[-2, 0, 2]
[-3, -1, 1, 3]
[1, 2, 3]
[-3, -2, -1]

后来:借鉴@Kos的思路,你可以这样写 split_list

def split_list(myList, option):
    predicate = negative_list if not option else even_list
    return predicate(myList)

或者:

def split_list(myList, option):
    predicates = [negative_list, even_list]
    return predicates[option](myList)

如果 for-loop 在一个被调用的函数里的列表推导中,我不太确定这是否符合你的需求。

另外:“函数名应该使用小写字母,必要时用下划线分隔单词,以提高可读性。”

4

在这里使用循环有点多余,因为有一个标准的函数叫做 filter,它可以完成你想要的操作:返回一个新列表,这个列表里包含了原列表中符合特定条件的元素。

首先,我们来定义这些条件:

def is_even(x):
    return x % 2 == 0

def is_negative(x):
    return x < 0

然后你可以很简单地用 filter 来定义你的函数:

def splitList(myList, option):
    predicate = is_negative if option == 0 else is_even
    return filter(predicate, myList)
0

我觉得这就是你想要实现的效果:

def splitList(myList,option):

    result = []

    if option == 0:
        for item in myList:
            if (item < 0):
                result.append(item)
    elif option == 1:
        for item in myList:
            if (item % 2 == 0):
                result.append(item)
    else:
        return "Option Error"

    return sorted(result)

print splitList([1,-3,5,7,-9,-11,0,2,-4], 0)
print splitList([1,-3,5,7,-9,-11,0,2,-4], 1)
print splitList([1,-3,5,7,-9,-11,0,2,-4], 2)

输出结果:

[-11, -9, -4, -3]
[-4, 0, 2]
Option Error

撰写回答