Home > front end >  If String(s) in List, output the index of List and which String(s) was found
If String(s) in List, output the index of List and which String(s) was found

Time:07-02

py_list = ['Big apple pie','Small blueberry Pie','Cold Cherry Pie','Hot keylime pie']

keywords = ['blueberry','keylime']

for text in py_list:
    if any(xs in text for xs in keywords):
        itemlist = (py_list.index(text))
        print(xs,"was found in index: ", itemlist " of py_list")

Traceback (most recent call last): NameError: name 'xs' is not defined on line 7

How could I get output to be:

blueberry was found in index: 1 of py_list
keylime was found in index: 3 of py_list

CodePudding user response:

Firstly, you're misusing the any function. any() accepts an iterable and returns True when it finds that one of the items in the iterable is True or has a True boolean value.

Secondly, you'll need to declare the variable in the for loop at a higher hierarchy for it to reach the statements within the if statement, like so.

py_list = ['Big apple pie', 'Small blueberry Pie', 'Cold Cherry Pie', 'Hot keylime pie']

keywords = ['blueberry', 'keylime']

for text in py_list:
    for xs in keywords:
        if xs in text:
            itemlist = (py_list.index(text))
            print(xs, "was found in index: ", itemlist, " of py_list")

CodePudding user response:

The accepted answer can be improved by eliminating the need for a belated look-up of the index as follows:

py_list = ['Big apple pie','Small blueberry Pie','Cold Cherry Pie','Hot keylime pie']

keywords = ['blueberry','keylime']

for i, s in enumerate(py_list):
    for k in keywords:
        if k in s:
            print(f'{k} was found in index: {i} of py_list')

Output:

blueberry was found in index: 1 of py_list
keylime was found in index: 3 of py_list
  • Related