试试这个:
def get_sublist_index(lists, item):
for sublist in lists:
if item in sublist:
return lists.index(sublist), sublist.index(item)
>>> L=[[1,2,3],[4,5,6]]
>>> get_sublist_index(L, 3)
(0, 2)
或者获取每个项目:
def get_sublist_index(lists, item):
for sublist in lists:
if item in sublist:
yield lists.index(sublist), sublist.index(item)
>>> L=[[1,2,3],[4,3,6]]
>>> get_sublist_index(L, 3)
<generator object get_sublist_index at 0x1056c5e08>
>>> [i for i in get_sublist_index(L, 3)]
[(0, 2), (1, 1)]
或者如果您不想使用生成器:
def get_sublist_index(lists, item):
outList = []
for sublist in lists:
if item in sublist:
outList.append((lists.index(sublist), sublist.index(item)))
return outList
>>> get_sublist_index(L, 3)
[(0, 2), (1, 1)]
>>>
L=[[1,2,3],[4,5,6],[2,3,4,5,3]]
a = 3
print([(i,j) for i,x in enumerate(L) if a in x for j,b in enumerate(x) if b == a])
#[(0, 2), (2, 1), (2, 4)]
也许是类似于这样:
def find_sublist(outer, what):
for i, lst in enumerate(outer):
try:
return i, lst.index(what)
except ValueError:
pass
实际上,output = [0][2]
会抛出异常。我不确定您的意思是什么。您是否需要一个包含两个元素的元组?我将假设您确实需要。
您也可以使用更加优雅的方式,例如:
In [8]: [(i, sublist.index(3)) for i, sublist in enumerate(L) if 3 in sublist]
Out[8]: [(0, 2)]
In [9]: [(i, sublist.index(4)) for i, sublist in enumerate(L) if 4 in sublist]
Out[9]: [(1, 0)]
find_sublist(L, 3)
only gives me an output of 0 and the OP says the output should be 0, 2
- rassar使用 numpy.where 和 numpy.transpose 方法的一行解决方案(初始输入数组已扩展以涵盖复杂情况):
import numpy as np
L = [[1,2,3],[4,3,6]] # 3 occurs twice
output = np.transpose(np.where(np.array(L) == 3))
print(output)
[[0 2]
[1 1]]
L = [[1,2,3],[4,3,6]]
),则返回:array([[0, 1], [2, 1]])
。 - rassar[place1x, place1y], [place2x, place2y]
时,它返回了 [place1x, place2x], [place1y, place2y]
。 - rassar如果需要索引和序列,请始终使用enumerate
:
def find_index(l, val=3):
# res holds results
res = []
# Go through every sublist in l
# index1 indicates which sublist we check
for index1, sublist in enumerate(l):
# Go through every item in sublist
# index2 indicates which item we check
for index2, item in enumerate(sublist):
# append to result if we find a match
if item == val:
res.append([index1, index2])
return res
L = [[1, 2, 3], [4, 5, 6, 4, 3], [3, 3, 3]]
find_index(L)
[[0, 2], [1, 4], [2, 0], [2, 1], [2, 2]]
more_itertools.locate
}}返回索引字典。
代码
import more_itertools as mit
def indices(iterable, item):
"""Return a dict of indices of all located items."""
d = {}
for i, sub in enumerate(iterable):
val = list(mit.locate(sub, lambda x: x == item))
if not val:
continue
d[i] = val
return d
演示
给定浅层嵌套的可迭代对象:
indices([[1, 2, 3], [5, 6, 7]], 3)
# {0: [2]}
indices([[1, 2, 3], [5, 6, 7], [2, 3, 3]], 3)
# {0: [2], 2: [1, 2]}
这里记录了多个出现的情况。
output = [0][2]
的含义,因为这肯定会引发异常。 - user1781434