【问题标题】:Use list of nested indices to access list element使用嵌套索引列表访问列表元素
【发布时间】:2017-04-18 01:58:30
【问题描述】:

索引列表(称为“indlst”)如何对应于元素 [1][0] 和 [3][1] 的索引列表,例如 [[1,0]、[3,1,2]] [2] 一个给定的列表(称为“lst”),可以用来访问它们各自的元素吗?例如,给定

    indlst = [[1,0], [3,1,2]]
    lst = ["a", ["b","c"], "d", ["e", ["f", "g", "h"]]]
    (required output) = [lst[1][0],lst[3][1][2]]

输出应该对应于 ["b","h"]。我不知道从哪里开始,更不用说找到一种有效的方法了(因为我不认为解析字符串是最pythonic 的方法)。

EDIT: 我应该提到索引的嵌套级别是可变的,所以[1,0] 有两个元素,[3,1,2] 有三个,依此类推。 (示例相应更改)。

【问题讨论】:

  • 我认为输出将是 ['b','f']
  • 你有一个列表,你有索引,只需使用这些索引引用列表中的元素。
  • @Iron 困难的部分来自于事先不知道有多少索引来引用单个给定元素。因此,我不能像典型的那样使用 i 和 j 引用元素,而是不知道需要多少变量。

标签: python list indexing nested


【解决方案1】:

递归可以从嵌套列表中抓取任意/深度索引的项目:

indlst = [[1,0], [3,1,2]]
lst = ["a", ["b","c"], "d", ["e", ["f", "g", "h"]]]
#(required output) = [lst[1][0],lst[3][1][2]]


def nested_lookup(nlst, idexs):
    if len(idexs) == 1:
        return nlst[idexs[0]]
    return nested_lookup(nlst[idexs[0]], idexs[1::])

reqout = [nested_lookup(lst, i) for i in indlst]
print(reqout) 

dindx = [[2], [3, 0], [0], [2], [3, 1, 2], [3, 0], [0], [2]]    
reqout = [nested_lookup(lst, i) for i in dindx]
print(reqout)
['b', 'h']
['d', 'e', 'a', 'd', 'h', 'e', 'a', 'd']  

我还发现任意额外的零索引都可以:

    lst[1][0][0]
    Out[36]: 'b'

    lst[3][1][2]
    Out[37]: 'h'

    lst[3][1][2][0][0]
    Out[38]: 'h'

因此,如果您确实知道最大嵌套深度,则可以通过使用 .update() 字典方法将(变量数,较短的)索引列表值覆盖到以零开头的最大固定长度字典中来填充索引列表值 然后直接硬编码嵌套列表的索引,忽略任何“额外”的硬编码零值索引

低于硬编码 4 深度:

def fix_depth_nested_lookup(nlst, idexs):
    reqout = []
    for i in idexs:
        ind = dict.fromkeys(range(4), 0)
        ind.update(dict(enumerate(i)))
        reqout.append(nlst[ind[0]][ind[1]][ind[2]][ind[3]])
    return reqout

print(fix_depth_nested_lookup(lst, indlst))
['b', 'h']

【讨论】:

    【解决方案2】:

    您可以遍历并收集值。

    >>> for i,j in indlst:
    ...     print(lst[i][j])
    ... 
    b
    f
    

    或者,您可以使用简单的列表推导从这些值中形成一个列表

    >>> [lst[i][j] for i,j in indlst]
    ['b', 'f']
    

    编辑:

    对于可变长度,您可以执行以下操作:

    >>> for i in indlst:
    ...     temp = lst
    ...     for j in i:
    ...         temp = temp[j]
    ...     print(temp)
    ... 
    b
    h
    

    您可以使用 functions.reducelist comprehension 形成一个列表。

    >>> from functools import reduce
    >>> [reduce(lambda temp, x: temp[x], i,lst) for i in indlst]
    ['b', 'h']
    

    注意这是一个 python3 解决方案。对于 python2,你可以忽略 import 语句。

    【讨论】:

      【解决方案3】:

      你可以试试这个代码块:

      required_output = []
      for i,j in indlst:
          required_output.append(lst[i][j])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多