从具有特定索引的 python 列表中挑选出项目

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

我确定在 Python 中有一种很好的方法可以做到这一点,但我对这门语言还很陌生,所以请原谅我,如果这是一个简单的方法!

我有一个列表,我想从该列表中挑选出某些值。我要挑选的值是列表中索引在另一个列表中指定的值。

例如:

indexes = [2, 4, 5]
main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8]

输出将是:

[9, 2, 6]

(即 main_list 中索引为 2、4 和 5 的元素)。

我觉得这应该可以使用列表理解之类的东西来实现,但我无法弄清楚(特别是,我无法弄清楚如何在使用列表理解时访问项目的索引)。

python list indexing list-comprehension
8个回答
123
投票
[main_list[x] for x in indexes]

这将使用列表理解返回对象列表。


4
投票
t = []
for i in indexes:
    t.append(main_list[i])
return t

2
投票
map(lambda x:main_list[x],indexes)

2
投票

如果你擅长

numpy

import numpy as np
main_array = np.array(main_list) # converting to numpy array
out_array = main_array.take([2, 4, 5])
out_list = out_array.tolist() # if you want a list specifically

1
投票

我认为 Yuval A 的解决方案非常清晰和简单。但是如果你真的想要一个单行列表理解:

[e for i, e in enumerate(main_list) if i in indexes]

1
投票

作为列表理解的替代方法,您可以将

map
list.__getitem__
一起使用。对于大型列表,您应该会看到更好的性能:

import random

n = 10**7
L = list(range(n))
idx = random.sample(range(n), int(n/10))

x = [L[x] for x in idx]
y = list(map(L.__getitem__, idx))

assert all(i==j for i, j in zip(x, y))

%timeit [L[x] for x in idx]            # 474 ms per loop
%timeit list(map(L.__getitem__, idx))  # 417 ms per loop

对于惰性迭代器,您可以只使用

map(L.__getitem__, idx)
。注意在 Python 2.7 中,
map
返回一个列表,因此不需要传递给
list
.


0
投票

我注意到有两种可选的方法可以完成这项工作,通过循环或转向 np.array。然后我测试了这两种方法所需要的时间,结果表明当数据集很大时
【[main_list[x] for x in indexes]】比速度快3~5倍 【np.array.take()】
如果您的代码对计算时间敏感,则投票最高的答案是一个不错的选择。


0
投票
indexes = [2, 4, 5]
main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8]

#create an empty list to add your required output
new_list =[]

# lenth of the list indexes
length = len(indexes)
for i in range(length):

    # values of list indexes 
    new_indexes =indexes[i] 

    '''Use the values of indexes as index of mainlist and get
    values of main list for the respective indexes'''
    main_value = main_list[new_indexes]

    #appending values to the list new_list 
    new_list.append(main_value)
print(new_list) # output [9, 2, 6]
© www.soinside.com 2019 - 2024. All rights reserved.