如何快速搜索列表中的元素,在下面的最後一個命令的輸出中查找得到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
如何快速搜索列表中的元素,在下面的最後一個命令的輸出中查找得到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
結合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]
我搜索'10 .98.78.235',而不是['10 .98.78.235','1'] – irom
好像你想要這個:
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]]
你可以用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]
[Python中的可能的複製 - 找到索引列表中的項目](https://stackoverflow.com/questions/9553638/python-find-the-index-of-an-item-in-a-list-of-lists) – bhansa
你是什麼使用結構?看起來你可能會更好地使用字典(或轉換爲字典)。 – allo