joh*_*hns 5 python nested-lists sublist
给定这些子列表
lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]
Run Code Online (Sandbox Code Playgroud)
我试图找到其元素的位置,例如,字母“a”位于 0,0 但这一行
print(lst.index('a'))
Run Code Online (Sandbox Code Playgroud)
相反会产生以下错误: ValueError: 'a' is not in list
小智 0
您可以使用列表理解:
>>> lst=[['a', 'b', 'a', 'd', 'a'], ['f', 'g', 'a'], ['a','a','b']]
>>> [(i,j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j]=='a']
[(0, 0), (0, 2), (0, 4), (1, 2), (2, 0), (2, 1)]
Run Code Online (Sandbox Code Playgroud)