Home > other >  Find index position in list based on more than one partial string and using operator in python
Find index position in list based on more than one partial string and using operator in python

Time:06-08

Suppose you have a list mylist

mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]

how to find an index for element that have both 'aa' and '3'? I expect the value returned to 0 "aa123", 2 "aa354", 4 "ab334" and 5 "333aa".

there are some similar thread in stack overflow: Find all index position in list based on partial string inside item in list and Return index position in array based on a partial string in Python.

But when I tried to use 'and' but it returned to all index

mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
l = [i for i, s in enumerate(mylist) if ('aa' and '3') in s]
print(l)

output : [0, 1, 2, 3, 4, 5]

Thanks so much in advance, I would be very grateful if someone could help me with this problem

CodePudding user response:

You're almost there. The problem with your code is in if statement, ('aa' and '3') is evaluating as '3' which is present in each element of your list. You can check this by printing the output of print('aa' and '3'). Modify your if statement as below:

mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
idx = [i for i, s in enumerate(mylist) if "aa" in s and "3" in s]
print(idx)

Output:

[0, 2, 5]
  • Related