給定這些子串列
lst=[['a'/span>, 'b'/span>, 'c'/span>, 'd', 'e'], ['f', 'g', 'h'] ]
我試圖找到其元素的位置。 例如,字母'a'的位置是0,0 但這一行
print(lst.index('a'/span>)
相反,產生以下錯誤。 ValueError: 'a' 不在串列中
。uj5u.com熱心網友回復:
如果你的list有depth=2,你可以使用這個:
lst=[['a'/span>, 'b'/span>, 'c'/span>, 'd', 'e'], ['f', 'g', 'h']]
def fnd_idx(char, lst)。
pos = []
for x in range(len(lst)):
try:
idx = lst[x].index(char)
pos = [x,idx]
return pos
except ValueError:
pass
return None
輸出:
>>> print(fnd_idx('a'/span>, lst)
[0, 0]
>>> print(fnd_idx('g'/span>, lst))
[1, 1]
>>> print(fnd_idx('z', lst)
None(fnd_idx('z, lst)
uj5u.com熱心網友回復:
試試這個函式(只有一行代碼!):
def idx(lst, el)。
return next((i, sublst.index(el))
for i, sublst in enumerate(lst)
if el in sublst)。)
None)
因此,例如:
>>> idx(lst, 'a'/span>)
(0, 0)
>>> idx(lst, 'c'/span>)
(0, 2)
uj5u.com熱心網友回復:
lst=[['a'/span>, 'b'/span>, 'c'/span>, 'd', 'c'], ['f', 'g', 'h'] ]
searchvalue = 'f' 0
for index in lst:
if searchvalue in index:
print(counter, index.index(searchvalue))
counter =1
uj5u.com熱心網友回復:
你可以用numpy做這個,好處是你不必為嵌套串列的大小做任何硬編碼。
lst=[['a'/span>, 'b'/span>, 'c'/span>, 'd', 'e'], ['f', 'g', 'h']]
arr = np.array(lst, dtype=object)
for x in arr:
try:
print (x.index('a'/span>), x)
except:
pass。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333346.html
標籤:
上一篇:試圖反轉陣列元素
