根据另一个列表的索引从列表的列表中获取元素

问题描述 投票:0回答:5

我想检索列表列表中的特定元素,而不使用列表理解、循环或 Python 中的任何迭代方法。

例如,给出以下列表:

[[1,2,3,4],[3,4],[5,6,7]]

这个向量:

[0,0,1]

我想检索第 0 个列表中的第 0 个元素、第一个列表中的第 0 个元素以及第二个列表中的第 1 个元素:

[1,2,3,4][0] -> 1
[3,4][0] -> 3
[5,6,7][1] -> 6

这应该给出这个结果:

[1,3,6]

这在Python中可能吗?

python nested-lists
5个回答
2
投票

这是替代方案:

x = [[1,2,3,4],[3,4],[5,6,7]]
y = [0,0,1]
res = []
for i in range(len(x)):
    res.append(x[i][y[i]])

2
投票

使用列表理解

zip()
是实现这一目标的最Pythonic方法之一:

>>> my_list = [[1,2,3,4],[3,4],[5,6,7]]
>>> my_vector = [0,0,1]

>>> [x[i] for x, i in zip(my_list, my_vector)]
[1, 3, 6]

但是,由于 OP 无法使用 列表理解,这里有一个替代方案,使用

map()
lambda 表达式

>>> list(map(lambda x, y: x[y], my_list, my_vector))
[1, 3, 6]

在上面的解决方案中,当它们返回迭代器时,我将

map()
返回的对象显式转换为
list
。如果您可以使用 iterator,则无需进行类型转换。


2
投票

你可以使用

zip

l = [[1,2,3,4],[3,4],[5,6,7]]
i = [0,0,1]
op = []

for index, element in zip(i, l):
    op.append(element[index])

输出

[1, 3, 6]

1
投票

使用

map
你可以这样做

a = [[1,2,3,4],[3,4],[5,6,7]]
b = [0, 0, 1]
result = list(map(lambda x,y: x[y], a,b))
print(result)

输出

[1, 3, 6]

0
投票

在 Python 3.12 中,将

list.__getitem__
映射到两个列表非常快:

my_lists = [[1,2,3,4],[3,4],[5,6,7]]
my_indices = [3,0,1]

ans = list(map(list.__getitem__, my_lists, my_indices))

请注意,

map(op, zip(left,right))
最好写成
map(op, left, right)

由于我正在处理一个巨大的列表,我想使用指向我正在查找的元素的直接指针。

在Python中,“直接指针”将是一个可迭代的生成器表达式。生成器不会复制数据。因此,只要你有这两个列表,你就可以迭代排列:

from typing import Sequence, Iterable

def permuted(vector: Iterable[list], indices: Iterable[int]):
  return map(list.__getitem__, vector, indices)

for elem in permuted(my_lists, my_indices):
   print(elem)
© www.soinside.com 2019 - 2024. All rights reserved.