我想如何从列表列表中找到偶数 例子是:
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 :(得分:3)
虽然您没有明确说出来,但似乎您正在查找列表列表中每个列表中的最大偶数。从你的例子来看,如果没有偶数,你似乎希望程序加0。在这种情况下,这将起作用:
print [max(value for value in [0] + L if not value % 2) for L in list_of_lists]
答案 1 :(得分:2)
您可以使用一些不错的Pythonic语言结构从内到外构建此算法:
# 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]
答案 2 :(得分:1)
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]
答案 3 :(得分: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]
答案 4 :(得分: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功能:)
答案 5 :(得分: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,否则为0