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