有没有更好的方法从 Python 列表中提取任意索引?
我目前使用的方法是:
a = range(100)
s = [a[i] for i in [5,13,25]]
我想切片的数组为a,而[5,13,25]是我想获取的元素。它似乎比Matlab的等效写法更冗长:
a = 0:99;
s = a([6,14,26])
>>> from operator import itemgetter
>>> a = range(100)
>>> itemgetter(5,13,25)(a)
(5, 13, 25)
itemgetter(*indices)(list)
。 - Bar如果你是Matlab用户,但想要使用Python,请看看numpy:
In [37]: import numpy as np
In [38]: a = np.arange(100)
In [39]: s = a[[5,13,25]]
In [40]: s
Out[40]: array([ 5, 13, 25])
这里有一个NumPy和Matlab的比较,以及一个常用Matlab命令与其在NumPy中的对应表格。
并没有“现成的”方法 - 你所做的方法相当巧妙,你可以使用它。 如果你在代码中有很多这样的东西,你可能想使用一个继承于list的子类,该子类将使用与matlab类似的语法 - 它可以用几行代码完成,主要的负担是你必须始终使用这个新类而不是内置的列表。
class MyList(list):
def __getitem__(self, index):
if not isinstance(index, tuple):
return list.__getitem__(self, index)
return [self[i] for i in index]
而在控制台上:
>>> m = MyList(i * 3 for i in range(100))
>>> m[20, 25,60]
[60, 75, 180]
以下是优秀的被接受答案John La Rooy所做版本的更强壮的版本(参考答案链接)。它通过提供的doctests测试。它总是返回一个列表。
def slice_by_index(lst, indexes):
"""Slice list by positional indexes.
Adapted from https://dev59.com/vmox5IYBdhLWcg3wl1T4#9108109.
Args:
lst: list to slice.
indexes: iterable of 0-based indexes of the list positions to return.
Returns:
a new list containing elements of lst on positions specified by indexes.
>>> slice_by_index([], [])
[]
>>> slice_by_index([], [0, 1])
[]
>>> slice_by_index(['a', 'b', 'c'], [])
[]
>>> slice_by_index(['a', 'b', 'c'], [0, 2])
['a', 'c']
>>> slice_by_index(['a', 'b', 'c'], [0, 1])
['a', 'b']
>>> slice_by_index(['a', 'b', 'c'], [1])
['b']
"""
if not lst or not indexes:
return []
slice_ = itemgetter(*indexes)(lst)
if len(indexes) == 1:
return [slice_]
return list(slice_)
看起来你会做:
a = list(range(99))
s = [a[5], a[13], a[25]]
这似乎与Matlab版本几乎完全相同。
5
表示第六个元素。如果使用基于1的语言,则会有一个6
。那么Matlab为什么需要4
呢?难道它是从-1开始的吗? - John Machin