簡體   English   中英

在具有2個列表的字符串列表中搜索子字符串匹配項

[英]Searching for a substring match in a string list with 2 lists

我有2個要處理的清單。 第一個是nameList,它對應於我要在其中找到匹配項的名稱,第二個列表是該命名列表的狀態。 我希望能夠瀏覽第一個列表並在字符串中查找匹配項,如果存在匹配項,則將第一個列表中的元素抓取到新列表中,還可以抓取第二個列表中的相應元素以獲取名稱和狀態對。 我已經嘗試了幾種方法,但仍無法解決問題,並且在板上查看了各種列表理解問題,也沒有找到適合我的情況的解決方案。

例如,在下面的代碼中,我想獲取這兩個條目的“ abc-1”和“ abc-2”條目以及“ ok”和“ ok”狀態,並將其輸出為finalNameList和finalStatusList 。

對於任何人都可以提供的任何幫助,我將不勝感激。

在我當前的實現中,我收到類型錯誤:“期望的字符串或緩沖區”

import re
import os
import sys
import getopt
import pdb

nameList = ['abc-1', 'abc-2', 'def-1', 'def-2']
statusList = ['ok', 'ok', 'bad', 'bad']
scac = 'abc'


def scacFilter (scac, nameList, statusList):
    if not scac:
        newNameList = nameList
        newStatusList = statusList
    else:
        for i in nameList:
            if re.search(scac, i):
                name = nameList[i]
                status = statusList[i]
                newNameList.append(name)
                newStatusList.append(status)
            else:
                print 'no scac match'
    return newNameList, newStatusList


finalNameList, finalStatusList = scacFilter(scac, nameList, statusList)

i是一個整數。 因此,正則表達式正在搜索scac中以整數值定義的字符串。 即它在1搜索'abc'

創建for循環的更好方法是:

for i in nameList:

這樣, i實際上是nameList的字符串(即'abc-1''abc-2'等),而不是整數,因此,您將對打算使用的字符串執行正則表達式!

 import os nameList = ['abc-1', 'abc-2', 'def-1', 'def-2'] statusList = ['ok', 'ok', 'bad', 'bad'] scac = 'abc' def scacFilter (scac, nameList, statusList): resultList = [] resultVal = [] for val in nameList: if not val.find(scac): indexVal = nameList.index(val) resultList.append(nameList[indexVal]) resultVal.append(statusList[indexVal]) return resultList, resultVal finalNameList, finalStatusList = scacFilter(scac, nameList, statusList) print finalNameList print finalStatusList 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM