[英]Finding even numbers in lists of lists python
我想如何从列表列表中查找偶数。
示例是:
maximum_even_each_list_in_lol([[1,2,3],[6,5,4],[5,7,9]])
应该返回(最大偶数):
[2,6,0]
我发现如何从列表中从stackoverflow查找偶数:
def maximum_even_each_list_in_lol (lol):
evens=[]
for number in lol:
if is_even(number):
evens.append(number)
return evens
但我想知道如何做到这一点,以便它可以在列表中的每个列表中找到偶数。
尽管您没有明确说出来,但似乎您正在列表列表中的每个列表中寻找最大偶数。 从您的示例看来,如果没有偶数,您似乎希望程序加0。 在这种情况下,它将起作用:
print [max(value for value in [0] + L if not value % 2) for L in list_of_lists]
您可以使用一些不错的Python语言构造从内到外构建此算法:
# Function to determine if one number is even
is_even = lambda x : x%2==0
# Function to return just the even numbers of a list
just_evens = lambda x : filter(is_even, x)
# Function to return the maximum number in a list, or '0' if there is none
get_max = lambda x : max(x) if len(x) else 0
# Function to return the maximum even number of a list
max_even = lambda x : get_max(just_evens(x))
# Print out the maximum even number from each list:
map(max_even, [[1,2,3],[6,5,4],[5,7,9]])
这将打印出:
[2, 6, None]
python 3.4采用max的默认值,因此如果在过滤后没有偶数,我们可以返回0
作为默认值:
l = [[1,2,3],[6,5,4],[5,7,9]]
print([max(filter(lambda x: not x % 2,x),default=0) for x in l])
[2, 6, 0]
你快到了! :-)
检查内置的max函数的作用。
def maximum_even_each_list_in_lol (lol):
evens=[0] # Dirty trick to ensure that regardless of the `even` numbers
# found, you'll always have a zero among the results.
for number in lol:
if is_even(number):
evens.append(number)
print "I found these even numbers (%s) among %s" % (evens, lol)
return max(evens) # Return the maximum value among the `evens` list.
results = []
for lst in [[1,2,3],[6,5,4],[5,7,9]]:
print "Studying %s" % lst
results.append(maximum_even_each_list_in_lol(lst))
print "This is what I found: %s" % results
我添加了一些print
语句,以帮助遵循代码的作用。 上面的代码将输出:
Studying [1, 2, 3]
I found these even numbers ([0, 2]) among [1, 2, 3]
Studying [6, 5, 4]
I found these even numbers ([0, 6, 4]) among [6, 5, 4]
Studying [5, 7, 9]
I found these even numbers ([0]) among [5, 7, 9]
This is what I found: [2, 6, 0]
据我了解,您想遍历列表列表 ,从每个列表中获取最大的偶数,如果找不到偶数则为0。 然后是您的功能:
def maximum_even_each_list_in_lol(lol):
evens = []
for sublist in lol:
subevens = []
for number in sublist:
if (not number % 2):
subevens.append(number)
# As I understand you want to insert 0
# if no even numbers were found, right?
if not subevens:
subevens = [0]
evens.append(max(subevens))
return evens
# Testing
assert maximum_even_each_list_in_lol([[1,2,3],[6,5,4],[5,7,9]]) == [2,6,0]
确保阅读有关内置最大功能的信息:)
干得好:
>>> [ max(x) if len(x)>0 else 0 for x in [ list(filter(lambda x:x%2==0,x)) for x in a ]]
[2, 6, 0]
我使用lambda检查偶数,然后过滤以将值保存为true,如果列表长度大于0则为max,否则为max
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.