我需要从给定列表中选择一些元素,知道它们的索引.假设我想创建一个新列表,其中包含索引为1,2,5的元素,来自给定列表[-2,1,5,3,8,5,6].我做的是:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?像c = a [b]之类的东西?
在Python中,我有一个元素aList列表和一个索引列表myIndices.有什么方法可以一次性检索所有项目中aList的值作为索引myIndices吗?
例:
>>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> myIndices = [0, 3, 4]
>>> aList.A_FUNCTION(myIndices)
['a', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)