2017-10-19 35 views
0

如何快速搜索列表中的元素,在下面的最后一个命令的输出中查找得到True还有一种快速获取索引的方法(示例中为'0'和'2'),而不是通过列表循环?Python列举str

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

[Python中的可能的复制 - 找到索引列表中的项目](https://stackoverflow.com/questions/9553638/python-find-the-index-of-an-item-in-a-list-of-lists) – bhansa

+1

你是什么使用结构?看起来你可能会更好地使用字典(或转换为字典)。 – allo

回答

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] 

https://repl.it/MuGF

+0

我搜索'10 .98.78.235',而不是['10 .98.78.235','1'] – irom

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]] 
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]