拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何访问存盘在idx变量中的串列中的特定值?(Python)

如何访问存盘在idx变量中的串列中的特定值?(Python)

白鹭 - 2022-02-13 2077 0 0

我通过“特定程序”获得一个索引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 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *