【问题标题】:Python - search for string in arrayPython - 在数组中搜索字符串
【发布时间】:2014-10-10 20:09:54
【问题描述】:

我有一个字符串数组:

["aaa 1", "aaa 2", "bbb 2", "ccc 3", "ddd 4"]

我需要在这个向量中搜索一些字符串,但只搜索第一部分。例如,我需要以"aaa" 开头的字符串的位置(在本例中,为 0 和 1)。

我该怎么做?

【问题讨论】:

    标签: python arrays string


    【解决方案1】:

    您可以将list comprehensionenumeratestr.split 一起使用:

    >>> lst = ["aaa 1", "aaa 2", "bbb 2", "ccc 3", "ddd 4"]
    >>> [x for x,y in enumerate(lst) if y.split()[0] == "aaa"]
    [0, 1]
    >>>
    

    y.split()[0] 将字符串拆分为空格并返回第一个元素。因此:

    if y.split()[0] == "aaa"
    

    只检查每个字符串的第一部分。但是,如果字符串总是像您的示例中给出的那样,一个简单的in membership test 就足够了:

    [x for x,y in enumerate(lst) if "aaa" in y]
    

    【讨论】:

      【解决方案2】:

      我们enumeratestr.startswith

      >>> l =  ["aaa 1", "aaa 2", "bbb 2", "ccc 3", "ddd 4"]
      >>> print [ind for ind, ele in enumerate(l) if ele.startswith("aaa")]
      [0, 1]
      

      ind 是列表中每个元素的索引,ele 是每个元素,所以如果字符串以“aaa”开头,我们将索引添加到列表中

      如果没有机会在字符串的后半部分使用"aaa",或者仅使用in 的前半部分的子字符串将是最有效的

      [ind for ind, ele in enumerate(l) if "aaa" in ele]
      

      【讨论】:

        【解决方案3】:

        你有一个清单。为了浏览每个项目,您可以:

        for eachlistitem in listname:
            if eachlistem[:3] == "ABC": #this only checks first three char of current list item
                ##do something here like increment a counter
                ##add counter # to new list to have a list of locations
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-04
          • 2023-03-13
          • 2011-07-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多