[英]find the sublist whose first element is the maximum that is no greater than a given number
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
. 例如,我想在列表
a
找到子列表,这样它的第一个元素是最大元素,不大于3
。 The sublist is [2,'b']
. 子列表是
[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 : 1)使用filter生成满足
sl[0]<3
的条件的列表的子列表:
>>> filter(lambda sl: sl[0]<3, a)
[[1, 'a'], [2, 'b']]
1.a) You could use a list comprehension also: 1.a)您还可以使用列表理解:
>>> [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: 2)然后使用键函数找到该子集列表的最大值 :
>>> max([[1, 'a'], [2, 'b']], key=lambda sl: sl[0])
[2, 'b']
3) Combine -- one line -- no sort -- be happy... 3)结合-一行-没有排序-快乐...
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: 然后,您可以在导入您放置在模块中的任何模块之后,或者在您的环境中定义它之后,从Python调用它(带有或不带有条件的值,默认为4)。
>> my_list = # define your list here
>> smallest_match = get_first(my_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.