繁体   English   中英

查找其第一个元素是不大于给定数字的最大值的子列表

[英]find the sublist whose first element is the maximum that is no greater than a given number

我有一个子列表列表,每个子列表的第一个元素是一个数字。 我想找到其第一个元素是不大于给定数字的最大值的子列表。 我想知道如何实施?

例如,我想在列表a找到子列表,这样它的第一个元素是最大元素,不大于3 子列表是[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']

谢谢并恭祝安康!

>>> a=[[5,'d'] ,[1,'a'],[4,'c'],[2,'b'] ]
>>> max(filter(lambda sl: sl[0]<3, a), key=lambda sl: sl[0])
[2, 'b']

分解:

1)使用filter生成满足sl[0]<3的条件的列表的子列表:

>>> filter(lambda sl: sl[0]<3, a)
[[1, 'a'], [2, 'b']]

1.a)您还可以使用列表理解:

>>> [sl for sl in a if sl[0]<3]
[[1, 'a'], [2, 'b']]

2)然后使用键函数找到该子集列表的最大值

>>> max([[1, 'a'], [2, 'b']], key=lambda sl: sl[0])
[2, 'b']

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]

您可以使用类似以下内容的列表理解:

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

如果您经常这样做,则可以将其全部放入函数中:

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

然后,您可以在导入您放置在模块中的任何模块之后,或者在您的环境中定义它之后,从Python调用它(带有或不带有条件的值,默认为4)。

>> my_list = # define your list here
>> smallest_match = get_first(my_list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM