我通过“特定程序”获得一个索引idx
阵列。所以现在我想访问a
串列中的那些元素。在 R 中,这非常简单,但如果不使用 for 回圈,我无法在 python 中找到简单的解决方案。
下面是代码:
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"
我该如何解决这个简单的任务?谢谢
uj5u.com热心网友回复:
您可以使用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')
uj5u.com热心网友回复:
简短而简单的方法是使用串列或生成器推导式并使用带星号的表达式来解包其所有值:
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
行为,您可以创建自己的自定义类并__getitem__
稍微更改其方法以检查自变量是串列还是元组(或实际上任何具有__iter__
方法的物件),然后回传回传的内容R
(基本上使用相同的方法同上):
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
0 评论