【问题标题】:find the sublist whose first element is the maximum that is no greater than a given number找到第一个元素是不大于给定数字的最大值的子列表
【发布时间】:2014-07-07 03:46:54
【问题描述】:

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

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

感谢和问候!

【问题讨论】:

  • 如何打破关系?还是保证第一个元素是唯一的?
  • 是的,独一无二。 @Pradhan

标签: python


【解决方案1】:
>>> 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]&lt;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) 合并 -- 一行 -- 不排序 -- 快乐...

【讨论】:

    【解决方案2】:
    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]
    

    【讨论】:

      【解决方案3】:

      您可以使用类似以下的列表推导:

      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)
      

      【讨论】:

      • 谢谢。有没有比mylist[len(mylist)-1] 更简单的方法来获取列表的最后一个元素?
      • return new_list[0] 将在new_listNone 的情况下崩溃
      • @Tim,最后一个元素可以用my_list[-1]返回。任何负值都从-1 的最后一项开始,并在列表中向后索引。
      • @alfasin,是的,您可以使用 return new_list[0] if new_list[0] is not None else None 之类的东西来避免崩溃。
      • 无需排序:O(n log(n))操作
      猜你喜欢
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 2019-05-15
      • 2022-12-31
      • 2021-05-12
      • 1970-01-01
      • 2015-06-02
      • 2021-11-01
      相关资源
      最近更新 更多