Python枚举列表到str

时间:2017-10-19 14:23:19

标签: python-2.7 list

如何在列表列表中快速搜索元素,在下面的最后一个命令的输出中寻找 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

3 个答案:

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

https://repl.it/MuGF

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