从Python的奇数/偶数列表中删除偶数/奇数 [英] Remove an even/odd number from an odd/even Python list
问题描述
我试图更好地理解Python中的列表理解.我完成了一个关于代码战的在线挑战,提供了一个非常精致的解决方案,如下所示.
I am trying to better understand list comprehension in Python. I completed an online challenge on codewars with a rather inelegant solution, given below.
挑战是:
- 给出一个偶数和一个奇数的列表,返回奇数
- 给出一个奇数和一个偶数的列表,返回偶数
我对此的(不明确的)解决方案是:
My (inelegant) solution to this was:
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)
哪个工作正常,但似乎蛮力的.我是否认为以(c0>和e
等占位符列表开头的(大多数)函数很像菜鸟似的")错误?
Which works fine, but seems to be pretty brute force. Am I wrong in thinking that starting (most) functions with placeholder lists like o
and e
is pretty "noob-like"?
我想更好地理解为什么此解决方案适用于奇数列表,但在偶数列表上失败,以更好地理解列表理解:
I would love to better understand why this solution works for the odd list, but fails on the even list, in an effort to better understand list comprehension:
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
的位置.
预先感谢您提供任何见解.
Thanks in advance for any insights.
推荐答案
您的尝试失败,因为第一个if
是始终为真.您将始终拥有至少包含1个元素的列表;要么单数是奇数,并且您测试了一个带有所有偶数的列表,否则您的列表中有一个 one 偶数.只有 empty 列表为假.
Your attempt fails because the first if
is always going to be true. You'll always have a list with at least 1 element; either the odd one out is odd and you tested a list with all even numbers, otherwise you have a list with the one even number in it. Only an empty list would be false.
列表理解并不是这里的最佳解决方案,不是.尝试用最少的已检查元素数来解决问题(前两个元素,如果它们的类型不同,则获得第3个打破平局,否则进行迭代,直到找到不适合尾部的元素):>
List comprehensions are not the best solution here, no. Try to solve it instead with the minimum number of elements checked (the first 2 elements, if they differ in type get a 3rd to break the tie, otherwise iterate until you find the one that doesn't fit in the tail):
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个奇数;在这种情况下将返回第一个奇数),它也将无法处理.
The above will throw a StopIteration
exception if there are either fewer than 3 elements in the input iterable, or there is no exception to be found. It also won't handle the case where there is more than one exception (e.g. 2 even followed by 2 odd; the first odd value would be returned in that case).
这篇关于从Python的奇数/偶数列表中删除偶数/奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!