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

时间:2014-07-07 03:46:55

标签: python

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

例如,我想在列表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']

谢谢和问候!

3 个答案:

答案 0 :(得分:2)

>>> 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

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

3)结合 - 一条线 - 没有排序 - 快乐......

答案 1 :(得分:1)

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]

答案 2 :(得分:0)

你可以使用类似的列表理解:

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)