[英]Finding the index of an element in nested lists in python
我正在嘗試獲取python嵌套列表中元素的索引-例如[[a, b, c], [d, e, f], [g,h]]
(並非所有列表的大小相同) 。 我嘗試使用
strand_value= [x[0] for x in np.where(min_value_of_non_empty_strands=="a")]
但這僅返回一個空列表,即使該元素存在。 知道我在做什么錯嗎?
def find_in_list_of_list(mylist, char):
for sub_list in mylist:
if char in sub_list:
return (mylist.index(sub_list), sub_list.index(char))
raise ValueError("'{char}' is not in list".format(char = char))
example_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
find_in_list_of_list(example_list, 'b')
(0, 1)
假設您的清單是這樣的:
lst = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]
list_no = 0
pos = 0
for x in range(0,len(lst)):
try:
pos = lst[x].index('e')
break
except:
pass
list_no = x
list_no
給出列表號, pos
給出列表中的位置
您可以使用列表理解並枚舉
碼:
lst=[["a", "b", "c"], ["d", "e", "f"], ["g","h"]]
check="a"
print ["{} {}".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]
輸出:
['0 0']
腳步:
check
變量匹配,如果符合,則將其寫入列表 這給出了所有可能的輸出
即
代碼2:
lst=[["a", "b", "c","a"], ["d", "e", "f"], ["g","h"]]
check="a"
print ["{} {}".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]
給出:
['0 0', '0 3']
筆記:
這足夠嗎?
array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
for subarray in array:
if 'a' in subarray:
print(array.index(subarray), '-', subarray.index('a'))
這將返回0-0。第一個零是數組內子數組的索引,最后一個零是子數組內的'a'索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.