简体   繁体   中英

Searching for a substring match in a string list with 2 lists

I have 2 lists that I'm trying to work with. The first is a nameList that corresponds to names that I want to find a match within and the second list is a status of that named list. I want to be able to look through the 1st list and look for a match within the string and if there is a match grab the element in the first list into a new list and also grab the corresponding element in the second list to get a name and status pair. I've tried several approaches at this and have not been able to get it right and have looked at various list comprehension questions on the board and haven't been able to find a solution that works for my case.

For example in the code below, I would like to grab the 'abc-1' and 'abc-2' entries as well as the 'ok' and 'ok' status for both of those entries and output those as the finalNameList and finalStatusList.

I'd be grateful for any help anyone could provide.

In my current implementation I am getting a type error : 'expected string or buffer'

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 is an integer. So the regular expression is searching for the string defined in scac in an integer value. ie it's searching for 'abc' in 1 .

A better way to create your for loop would be:

for i in nameList:

This way, i is actually the string in nameList (ie 'abc-1' , 'abc-2' , etc...) and not an integer, thus you'll be performing your regex on the string you intend to!

 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM