【问题标题】:Python enumerate list to strPython枚举列表到str
【发布时间】:2018-03-31 15:05:45
【问题描述】:

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

【问题讨论】:

标签: python-2.7 list


【解决方案1】:

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

【讨论】:

  • 我搜索的是 '10.98.78.235',而不是 ['10.98.78.235', '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]

【讨论】:

    【解决方案3】:

    好像你想要这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 2013-04-25
      • 2023-02-26
      相关资源
      最近更新 更多