I have a list of sublists, and the first element of each sublist is a number. I would like to find the sublist whose first element is the maximum that is no greater than a given number. I wonder how to implement that?
For example, I would like to find the sublist in list a
, so that its first element is the maximum one which is no greater than 3
. The sublist is [2,'b']
.
>>> a=[[5,'d'] ,[1,'a'],[4,'c'],[2,'b'] ]
>>> a = sorted(a)
>>> a
[[1, 'a'], [2, 'b'], [4, 'c'], [5, 'd']]
>>> [3>=x for [x,_] in a]
[True, True, False, False]
>>> a[1]
[2, 'b']
Thanks and regards!
>>> a=[[5,'d'] ,[1,'a'],[4,'c'],[2,'b'] ]
>>> max(filter(lambda sl: sl[0]<3, a), key=lambda sl: sl[0])
[2, 'b']
Break that down:
1) Produce the sub list of the list of lists that meets the criteria of sl[0]<3
using filter :
>>> filter(lambda sl: sl[0]<3, a)
[[1, 'a'], [2, 'b']]
1.a) You could use a list comprehension also:
>>> [sl for sl in a if sl[0]<3]
[[1, 'a'], [2, 'b']]
2) Then find the max of that subset list using a key function:
>>> max([[1, 'a'], [2, 'b']], key=lambda sl: sl[0])
[2, 'b']
3) Combine -- one line -- no sort -- be happy...
def grab_max_pair(lst_of_pairs, num):
result = None
for pair in lst_of_pairs:
if result and pair[0] <= num:
if pair[0] > result[0]:
result = pair
elif pair[0] <= 3:
result = pair
return result
a=[[5,'d'] ,[1,'a'],[4,'c'],[2,'b'] ]
print grab_max_pair(a, 3) # prints [2,b]
You could use a list comprehension with something like:
a = # define your list here
new_list = [list for list in a if list[0] < 4] # only grab sub-lists that meet your criterion
new_list = sorted(new_list) # sort them now (shorter list)
result = new_list[0] # grab the first result
You could throw this all into a function if it is something that you do a lot:
def get_first(my_list, criterion=4):
new_list = [list for list in my_list if list[0] < criterion]
new_list = sorted(new_list)
return new_list[0] if new_list is not None else None # avoid a crash if new_list[0] does not have meaning
You could then call this (with or without a value for criterion, default is 4) from Python after importing whatever module you have placed it inside, or after defining it in your environment:
>> my_list = # define your list here
>> smallest_match = get_first(my_list)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.