按列表索引嵌套列表 [英] Indexing nested list by a list

查看:23
本文介绍了按列表索引嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个嵌套列表,如

<预><代码>>>>m= [[3, 1], [2, 7]]

我可以得到这样的元素

<预><代码>>>>米[1][0]2

如果索引在列表中给出,我如何获得相同的值,即 [1, 0]?

我正在寻找 Q 编程语言提供的具有 dot 就像下面的代码

q) m: (3 1; 2 7)q) m[1][0]2q) 米.1 02

解决方案

作为快速解决方案,您可以滥用 functools.reduce 像这样:

from functools import reducedef get_recursive(lst, idx_list):return reduce(list.__getitem__, [lst, *idx_list])

<预><代码>>>>y = [[3, 1], [2, 7]]>>>get_recursive(y, [0, 1])1>>>get_recursive(y, [1, 0])2

有很多极端情况需要处理(另外,您必须确保路径存在或处理出现的任何错误),但这应该可以帮助您入门.

given a nested list like

>>> m= [[3, 1], [2, 7]]

I can get an element like this

>>> m[1][0]
2

How can i get the same value if the index is given in a list, i.e. as [1, 0]?

I am looking for something that the Q programming language offers with dot like in code below

q) m: (3 1; 2 7)
q) m[1][0]
2
q) m . 1 0
2

解决方案

As a quick-n-dirty solution, you can abuse functools.reduce like this:

from functools import reduce
def get_recursive(lst, idx_list):
    return reduce(list.__getitem__, [lst, *idx_list])

>>> y = [[3, 1], [2, 7]]
>>> get_recursive(y, [0, 1])
1
>>> get_recursive(y, [1, 0])
2

There are quite a few corner cases to handle (plus you'd have to be sure the path exists or else handle any errors that arise) but this should get you started.

这篇关于按列表索引嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆