[英]How to change a list from saying true/false for even and odd numbers , to simply saying even or odd for each number?
[英]Remove an even/odd number from an odd/even Python list
我试图更好地理解Python中的列表理解。 我用一个不太雅致的解决方案完成了关于代码战的在线挑战,如下所示。
挑战是:
我对此的(模糊的)解决方案是:
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
类的占位符列表开头(大多数)功能非常“像noob一样”而错吗?
我想更好地理解为什么此解决方案适用于奇数列表,但在偶数列表上失败,以更好地理解列表理解:
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个元素的列表; 要么单数是奇数,并且您测试了所有偶数的列表,否则您的列表中有一个偶数。 只有一个空列表将为假。
列表理解不是最好的解决方案,不是。 尝试用最少的检查元素来解决问题(前两个元素,如果它们的类型不同,则获得第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个奇数;在这种情况下将返回第一个奇数)。
最有效的答案将变得有些丑陋。
def f(in_list):
g = (i for i in in_list)
first = next(g)
second = next(g) #The problem as described doesn't make sense for fewer than 3 elements. Let them handle the exceptions.
if first%2 == second%2:
a = first%2
for el in g:
if el%2 != a:
return el
else:
third = next(g)
if third%2 == first%2:
return second
else:
return first
except ValueError('Got a bad list, all evens or all odds')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.