简体   繁体   中英

How to return exact match on first element in the list

  • 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?

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 .

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