如何访问存储在 idx 变量中的列表中的特定值? (python)
How to access specific values inside a list that are stored in a idx variable? (python)
我通过“特定过程”获得索引idx
数组。所以现在我想访问 a
列表中的那些元素。
在 R 中,这非常简单,但我无法在 python 中找到不使用 for 循环的简单解决方案。
下面是代码:
a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
idx = [2,4,7,8]
print(a[idx]) # --> R approach
#output should be --> "word3" "word5" "word8" "word9"
我该如何解决这个简单的任务?谢谢
简短的方法是使用列表或生成器理解并使用带星号的表达式来解包其所有值:
a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
idx = [2,4,7,8]
print(*(a[i] for i in idx))
# Output:
# word3 word5 word8 word9
如果您想复制 R
行为,您可以创建自己的自定义 class 并稍微更改其 __getitem__
方法以检查参数是列表还是元组(或者任何具有 __iter__
方法的对象)然后 return what R
returns (基本上使用与上面相同的方法):
class List(list):
def __getitem__(self, index):
if hasattr(index, '__iter__'):
return [self[i] for i in index]
return super().__getitem__(index)
a = ["word1", "word2", "word3", "word4", "word5", "word6", "word7", "word8", "word9"]
b = List(a)
idx = [2, 4, 7, 8]
print(b[idx]) # add star before to print only the values without the list and stuff
您可以使用 operator.itemgetter
:
>>> from operator import itemgetter
>>> a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
>>> idx = [2,4,7,8]
>>> itemgetter(*idx)(a)
('word3', 'word5', 'word8', 'word9')
我通过“特定过程”获得索引idx
数组。所以现在我想访问 a
列表中的那些元素。
在 R 中,这非常简单,但我无法在 python 中找到不使用 for 循环的简单解决方案。
下面是代码:
a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
idx = [2,4,7,8]
print(a[idx]) # --> R approach
#output should be --> "word3" "word5" "word8" "word9"
我该如何解决这个简单的任务?谢谢
简短的方法是使用列表或生成器理解并使用带星号的表达式来解包其所有值:
a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
idx = [2,4,7,8]
print(*(a[i] for i in idx))
# Output:
# word3 word5 word8 word9
如果您想复制 R
行为,您可以创建自己的自定义 class 并稍微更改其 __getitem__
方法以检查参数是列表还是元组(或者任何具有 __iter__
方法的对象)然后 return what R
returns (基本上使用与上面相同的方法):
class List(list):
def __getitem__(self, index):
if hasattr(index, '__iter__'):
return [self[i] for i in index]
return super().__getitem__(index)
a = ["word1", "word2", "word3", "word4", "word5", "word6", "word7", "word8", "word9"]
b = List(a)
idx = [2, 4, 7, 8]
print(b[idx]) # add star before to print only the values without the list and stuff
您可以使用 operator.itemgetter
:
>>> from operator import itemgetter
>>> a = ["word1","word2","word3","word4","word5","word6","word7","word8","word9"]
>>> idx = [2,4,7,8]
>>> itemgetter(*idx)(a)
('word3', 'word5', 'word8', 'word9')