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']
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.