【问题标题】:Searching for list in list python在列表python中搜索列表
【发布时间】:2018-06-15 04:36:37
【问题描述】:

假设我有以下包含其他小列表的 main_list:

main_list = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

我想找到知道 small_list 的索引 0 和 1 的 small_list。例如,我怎样才能创建一个 getlist() 函数:

getlist(4,5) = [4, 5, 6, 7]
getlist(0,1) = [0, 1, 2, 3]
getlist(5,5) = None
getlist(9,10) = None

【问题讨论】:

  • 我没听明白。
  • 这太宽泛了。你如何处理负指数?你如何处理切片?为什么要根据内部列表指定开始,而根据外部列表指定结束 - 开始?

标签: python arraylist computer-science


【解决方案1】:

最简单的方法是将列表映射到字典,其中的键设置为您不想检索的内容。这可以按照下面的示例使用列表推导式快速完成。

>>> main_list = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

>>> indexed_list = { (i[0], i[1]) : i for i in main_list }

>>> indexed_list.get( (0,1) )
[0, 1, 2, 3]

>>> indexed_list.get( (4,5) )
[4, 5, 6, 7]

>>> indexed_list.get( (5,5) )
None

【讨论】:

  • 太好了。谢谢!没有意识到字典键可以定义为元组。
  • 可以定义为任何东西,真正的底层键是您使用的任何实体的对象哈希。
【解决方案2】:

下面的代码应该可以解决您的问题,或者至少让您走上正轨。如果您需要,也可以通过here on OnlineGDB 进行进一步修改。

main_list = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

def getlist(idx0, idx1):
    # Assumes there isn't a match, unless one is found
    target_list = None

    # Loops through the list of lists, checking for a match with the characters at index 0 and 1
    for sub_list in main_list:
        if idx0 == sub_list[0] and idx1 == sub_list[1]:
            target_list = sub_list

    # returns the target list (if it found) or None (if it isn't)
    return target_list

print(getlist(4,5))
>>[4, 5, 6, 7]
print(getlist(0,1))
>>[0, 1, 2, 3]
print(getlist(5,5))
>>None
print(getlist(9,10))
>>None

【讨论】:

    【解决方案3】:

    检查切片列表可以在这里工作,如果有多个匹配列表的起始索引类似于参数,这也可以工作。

    >>> main_list = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
    >>> def get_list(tup, list_group):
    ...     return [list_ for list_ in list_group if list_[:2] == list(tup)]
    ...
    >>> print(get_list((0, 1), main_list))
    [[0, 1, 2, 3]]
    >>> main_list = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [0, 1, 10, 7]]  # multiple occurence
    >>> print(get_list((0, 1), main_list))
    [[0, 1, 2, 3], [0, 1, 10, 7]]
    

    【讨论】:

      【解决方案4】:

      这是一种对元素进行分类的奇怪方式。有更合适的方式来存储您的数据 lice 字典。

      main_list = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
      def getlist(a,b):
          for sub_list in main_list:
              if [a,b] == sub_list[0:2]:
                  return sub_list
      
      >>> print (getlist(4,5))
      >>> print (getlist(2,1))
      [4, 5, 6, 7]
      None
      

      【讨论】:

      • 第四行有错字,应该是sub_list
      猜你喜欢
      • 1970-01-01
      • 2022-11-12
      • 2013-03-06
      • 2018-04-13
      • 2012-11-21
      • 2023-01-04
      • 2014-05-01
      • 2020-07-11
      • 1970-01-01
      相关资源
      最近更新 更多