a = [[1,2,3],[4,5,6]]
我想得到和得到和。0
_ _ _1
2
3
1
4
5
6
当然我可以做这样的事情:
def get_index(my_list, my_item):
for i, j in enumerate(my_list):
if my_item in j:
return i
raise ValueError("Item not in any list")
有更好的方法吗?
更新答案:
由于 OP zenply 的输入,这是我原始答案的改进版本。
b = [[1,2,3],[4,5,6],[1,4,5], [4,7,8]]
def create_dict_2(a):
my_dict = {}
for index, sublist in enumerate(a):
for ele in sublist:
if not ele in my_dict:
my_dict[ele] = index
return my_dict
结果:
>>> my_dict = create_dict(b)
>>> my_dict[4]
1
>>> my_dict[5]
1
>>> my_dict[1]
0
>>> my_dict[7]
3
不确定这是否更具可读性,但它确实可以处理其中包含多个子列表的情况:
def get_index(my_list, my_item):
indices = [i for i, sublist in enumerate(my_list) if my_item in sublist]
if len(indices) == 1:
return indices[0]
raise ValueError("Item not in any list or in multiple lists")