Skip to main content
 首页 » 编程设计

python之从奇数/偶数 Python 列表中删除偶数/奇数

2025年05月04日31飞鱼

我正在尝试更好地理解 Python 中的列表推导式。我使用下面给出的相当不优雅的解决方案完成了关于 codewars 的在线挑战。

挑战是:

  1. 给定一个偶数和一个奇数的列表,返回奇数
  2. 给定一个奇数和一个偶数的列表,返回偶数

我的(不雅的)解决方案是:

def find_outlier(integers): 
    o = [] 
    e = [] 
    for i in integers: 
        if i % 2 == 0: 
            e.append(i) 
        else: 
            o.append(i) 
    # use sums to return int type 
    if len(o) == 1: 
        return sum(o) 
    else: 
        return sum(e) 

效果很好,但似乎很蛮力。我是否认为以 o 和 e 等占位符列表开始(大多数)函数是非常“菜鸟式”的?

我很想更好地理解为什么这个解决方案适用于奇数列表,但在偶数列表上失败,以便更好地理解列表理解:

def find_outlier(integers): 
    if [x for x in integers if x % 2 == 0]: 
       return [x for x in integers if x % 2 == 0] 
    elif [x for x in integers if x % 2 != 0]: 
       return [x for x in integers if x % 2 != 0] 
    else: 
        print "wtf!" 
 
o = [1,3,4,5] 
e = [2,4,6,7] 
 
In[1]: find_outlier(o) 
Out[1]: [4] 
 
In[2]: find_outlier(e) 
Out[2]: [2, 4, 6] 

Out[2] 应该返回 7。

提前感谢您的任何见解。

请您参考如下方法:

您的尝试失败了,因为第一个 if 总是为真。您将始终拥有一个至少包含 1 个元素的列表;要么奇数是奇数,你测试了一个包含所有偶数的列表,否则你有一个包含 one 偶数的列表。只有空列表是错误的。

列表理解不是这里最好的解决方案,不是。尝试使用最少数量的检查元素来解决它(前 2 个元素,如果它们的类型不同,则获得第 3 个元素以打破平局,否则迭代直到找到不适合尾部的元素):

def find_outlier(iterable): 
    it = iter(iterable) 
    first = next(it) 
    second = next(it) 
    parity = first % 2 
    if second % 2 != parity: 
        # odd one out is first or second, 3rd will tell which 
        return first if next(it) % 2 != parity else second 
    else: 
        # the odd one out is later on; iterate until we find the exception 
        return next(i for i in it if i % 2 != parity) 

如果输入可迭代对象中的元素少于 3 个,或者没有发现异常,以上代码将抛出 StopIteration 异常。它也不会处理存在多个异常的情况(例如,2 个偶数后跟 2 个奇数;在这种情况下将返回第一个奇数值)。