如何在列表列表中快速搜索元素,在下面的最后一个命令的输出中寻找 True 。 还有一种快速获取索引的方法(示例中为'0'和'2')而不是通过列表循环?
l=[['10.98.78.235', '1'], ['10.98.78.236', '2'], ['10.98.78.235', '10']]
>>> ['10.198.78.235', '1'] in l
True
>>> '10.198.78.235' in l
False
答案 0 :(得分:2)
将list comprehension
与索引语法和enumerate
l=[['10.98.78.235', '1'], ['10.98.78.236', '2'], ['10.98.78.235', '1']]
search=['10.98.78.235', '1']
indexes=[index for index,item in enumerate(l) if search in [item] ] ]
print indexes
将产生:
[0, 2]
或:
l=[['10.98.78.235', '1'], ['10.98.78.236', '2'], ['10.98.78.235', '10']]
search='10.98.78.235'
indexes=[index for index,item in enumerate(l) if search in item ]
print indexes
将产生:
[0, 2]
答案 1 :(得分:2)
您可以使用numpy
:
import numpy as np
l=np.array([['10.98.78.235', '1'], ['10.98.78.236', '2'], ['10.98.78.235', '10']])
matches = np.where((l == '10.98.78.235'))
positions = np.transpose(matches)
print positions
给出列表中每个维度的匹配列表(即行的第一个列表,列的第二个列表):
[[0 0]
[2 0]]
如果您只想获取行,则无需使用transpose
:
rows = matches[0]
答案 2 :(得分:1)
好像你想要这个:
search = ['10.98.78.235', '1']
result = [i for i, item in enumerate(l) if item[0] == search[0] and search[1] in item[1]]