[英]how can I get the index of the item in a list that contains the string being search (within the list) in python
[英]How can I get the index of a nested list item?
什么是獲取嵌套列表項索引的有效且pythonic方法?
例如:
some_list = [ [apple, pear, grape], [orange, plum], [kiwi, pineapple] ]
如何獲取“李子”的索引?
嘗試這個:
[(i, el.index("plum")) for i, el in enumerate(some_list) if "plum" in el]
輸出:
[(1, 1)]
通過嵌套列表的索引進行簡單迭代(不過僅適用於兩個級別的情況)。
def findelm(element, list):
x = 0
while x < len(list):
y = 0
while y < len(list[x]):
if list[x][y] == element: print "({},{})".format(x,y)
y = y + 1
x = x + 1
值得注意的是,如果列表元素不是列表本身,則失敗。
即:
輸入(失敗情況-所選元素未列出):
list = ["hey", "ho", ["hi", "haha", "help"], "hooha"]
findelm("hey", list)
輸出(失敗情況-所選元素未列出):
# Nothing!
VS
輸入(幸運的情況-選定元素為列表):
list = ["hey", "ho", ["hi", "haha", "help"], "hooha"]
findelm("haha", list)
輸出(幸運的情況-選定元素為列表):
(2,1)
VS
輸入(適當的用例):
list = [["hey"], ["ho"], ["hi", "haha", "help"], ["hooha"]]
findelm("hey", list)
輸出(適當的用例):
(0,0)
這里有些例子:
apple = some_list[0][0]
plum = some_list[1][1]
kiwi = some_list[2][0]
為了操縱您的列表some_list
,我將其子元素轉換為字符串以便處理它們。 因此,如果有
>>> some_list = [
['apple', 'pear', 'grape'],
['orange', 'plum'],
['kiwi', 'pineapple']
]
並且想要找到字符串元素'plum'
的索引和子索引
>>> to_find = 'plum'
然后
>>> [(index_,sub_list.index(to_find))\
for index_, sub_list in enumerate(some_list)\
if to_find in sub_list]
[(1, 1)]
將獲得您想要的索引。
設定
a = [ ['apple', 'pear', 'grape'], ['orange', 'plum'], ['kiwi', 'pineapple'] ]
Out[57]: [['apple', 'pear', 'grape'], ['orange', 'plum'], ['kiwi', 'pineapple']]
解
#Iterate the list of lists and build a list of dicts and then merge the dicts into one dict with words as keys and their index as values.
dict(sum([{j:[k,i] for i,j in enumerate(v)}.items() for k,v in enumerate(a)],[])).get('plum')
Out[58]: [1, 1]
dict(sum([{j:[k,i] for i,j in enumerate(v)}.items() for k,v in enumerate(a)],[])).get('apple')
Out[59]: [0, 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.