我需要从给定的列表中选择一些元素,知道它们的索引。假设我想创建一个新列表,其中包含从给定列表[- 2,1,5,3,8,5,6]中索引为1,2,5的元素。我所做的是:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
有什么更好的办法吗?比如c = a[b] ?
我需要从给定的列表中选择一些元素,知道它们的索引。假设我想创建一个新列表,其中包含从给定列表[- 2,1,5,3,8,5,6]中索引为1,2,5的元素。我所做的是:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
有什么更好的办法吗?比如c = a[b] ?
当前回答
截至2022年6月,最新熊猫==1.4.2的结果如下。
注意,简单的切片不再可能,基准测试结果更快。
import timeit
import pandas as pd
print(pd.__version__)
# 1.4.2
pd.Series([-2, 1, 5, 3, 8, 5, 6])[1, 2, 5]
# KeyError: 'key of type tuple not found and not a MultiIndex'
pd.Series([-2, 1, 5, 3, 8, 5, 6]).iloc[[1, 2, 5]].tolist()
# [1, 5, 5]
def extract_multiple_elements():
return pd.Series([-2, 1, 5, 3, 8, 5, 6]).iloc[[1, 2, 5]].tolist()
__N_TESTS__ = 10_000
t1 = timeit.timeit(extract_multiple_elements, number=__N_TESTS__)
print(round(t1, 3), 'seconds')
# 1.035 seconds
其他回答
这里有一个更简单的方法:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [e for i, e in enumerate(a) if i in b]
有点像python的方式:
c = [x for x in a if a.index(x) in b]
选择:
>>> map(a.__getitem__, b)
[1, 5, 5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)
截至2022年6月,最新熊猫==1.4.2的结果如下。
注意,简单的切片不再可能,基准测试结果更快。
import timeit
import pandas as pd
print(pd.__version__)
# 1.4.2
pd.Series([-2, 1, 5, 3, 8, 5, 6])[1, 2, 5]
# KeyError: 'key of type tuple not found and not a MultiIndex'
pd.Series([-2, 1, 5, 3, 8, 5, 6]).iloc[[1, 2, 5]].tolist()
# [1, 5, 5]
def extract_multiple_elements():
return pd.Series([-2, 1, 5, 3, 8, 5, 6]).iloc[[1, 2, 5]].tolist()
__N_TESTS__ = 10_000
t1 = timeit.timeit(extract_multiple_elements, number=__N_TESTS__)
print(round(t1, 3), 'seconds')
# 1.035 seconds
你可以使用operator.itemgetter:
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)
或者你可以使用numpy:
import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]
但说真的,你现在的解决方案很好。这可能是其中最简洁的一个。