我通過“特定程序”獲得一個索引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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/396510.html
上一篇:將字典展平并將其轉換為串列
下一篇:在串列中查找最舊并回傳最舊的串列
