Home > Software engineering >  How to return exact match on first element in the list
How to return exact match on first element in the list

Time:10-01

  • I have list I need to append the into another list which matches
  • The exact match should come at first
  • then it matches related matched
  • if a = ['mnoabc', 'defabc', 'abc', 'abcdef', 'ijk', 'lmn'] I am searching 'abc' then 'abc' should come first then 'abcdef', then 'mnoabc', 'defabc'
  • Not worried ordering of about mnoabc', 'defabc'. if 'abc' is coming at start of the string then it should append to list at beginning
a = ['mnoabc', 'defabc', 'abc', 'abcdef', 'ijk', 'lmn']
m = []
for i in a:
    if 'abc' in i:
        m.append(i)
m  

My out>> ['mnoabc', 'defabc', 'abc', 'abcdef']

Expected >> [ 'abc', 'abcdef','mnoabc', 'defabc']

  • Do i need to do regex for this?

CodePudding user response:

You can use insert to insert an item at a specified position. Try the following:

a = ['mnoabc', 'defabc', 'abc', 'abcdef', 'ijk', 'lmn']

m = []
num_startswith = 0

for i in a:
    if i == 'abc':
        m.insert(0, i)
        num_startswith  = 1
    elif i.startswith('abc'):
        m.insert(num_startswith, i)
        num_startswith  = 1
    elif 'abc' in i:
        m.append(i)

print(m) # ['abc', 'abcdef', 'mnoabc', 'defabc']

The variable num_startswith keeps track of where to insert a word that starts with abc.

CodePudding user response:

Using startswith() method we can check whether the string startswith substring 'abc'.

a = ['mnoabc', 'defabc', 'abc', 'abcdef', 'ijk', 'lmn']
m = []
for i in a:
    if i.startswith('abc'):
        m.append(i)
for i in a:
    if(i not in m):
        if 'abc'in i:
            m.append(i)
        
print(m) //['abc', 'abcdef', 'mnoabc', 'defabc']
  • Related