简体   繁体   中英

Get index of element in list that has specific substring

So I am building a stock finder project thing and I am looking to find stock tickers for stock names that contain a sub-string of the full name.

For example passing Apple as stockName would return AAPL because Apple is a substring of Apple, Inc. Same for Microsoft or Micros returning MSFT because Microsoft or Micros being a substring of Microsoft Corporation.

This is my existing code that returns errors if I put in a substring:

def getStockTicker(stockName):
    return companyTickers[companyNames.index(stockName)]

Does anyone has any ideas?

EDIT: I have handled the error so that if nothing is found in companyNames it returns a ValueError

I think that two separate lists, one of company names and one of company ticker Ids, is not the right data structure.

Are you familiar with the Python dict ? It maps keys to values. If you use the company name as the key and the ticker symbol as the value, declaring a dict would look like this:

companies = {
    'Apple, Inc.': 'AAPL',
    'Microsoft Corporation': 'MSFT'
}

And retrieving a given ticker symbol using the whole name looks like:

companies['Apple, Inc.']  # returns 'AAPL'

As for retrieving tickers based on a substring, it's perfectly doable. One thing to be wary of: the same substring might match multiple keys so you want to return a list of possible matches instead of the first possible match.

companies = {...}

def get_ticker_symbol(company):
    return [value for key, value in companies.items() if company in key]

stockName in someFullString will tell you if stockName is a substring of someFullString .

Given that, you can create a generator containing only string whose stockName is a substring of and retrieve the index of the first one, if any:

def getStockTicker(stockName):
    for fullString in (s for s in companyNames if stockName in s):
        return companyTickers[companyNames.index(fullString)]
    # at this point, stockName is not a substring of anything in compagnyNames
    return None # or raise an exception, or whatever

There's probably no other way than to iterate over the companyNames and check if it contains stockName .

def getStockTicker(stockName):
    for index, companyName in enumerate(companyNames):
        if stockName in companyName: 
            return companyTickers[index]

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