Reputation: 217
I'm trying to find out a string from list. Here's the code:
wordlist = ['gedit','leafpad','qstardict','stardict']
letters = str('stardict')
for item in wordlist:
if item.find(letters) != -1:
print item
It's showing 'qstardict' first and then 'stardict'. But I want it to show 'stardict' first. Please help me.
Upvotes: 0
Views: 217
Reputation: 180917
EDIT: A last attempt to do what you're asking, if this is not what you want, please update the question with a complete description of what you need help with;
This gets all words that start with your substring, in alphabetical order;
result = sorted(x for x in wordlist if x.startswith(letters))
Upvotes: 1
Reputation: 27575
This ?
wordlist = ['stardictionaries','hop','stardicto',
'stardictionaria', 'jumper',
'gedit','leafpad','qstardict',
'stardictionary','stardict',]
def seurch1(deb,wordlist):
for item in wordlist:
if item.startswith(deb):
yield item
def seurch2(deb,wordlist):
L = len(deb)
for item in wordlist:
if item[0:L]==deb:
yield item
from pprint import pprint
pprint( list(seurch1('stardict',wordlist)) )
print
pprint( sorted(seurch1('stardict',wordlist),key=len) )
print '--------------------'
pprint( list(seurch2('stardict',wordlist)) )
print
pprint( sorted(seurch2('stardict',wordlist),key=len) )
I think that seurch2()
is faster
result
['stardictionaries',
'stardicto',
'stardictionaria',
'stardictionary',
'stardict']
['stardict',
'stardicto',
'stardictionary',
'stardictionaria',
'stardictionaries']
--------------------
['stardictionaries',
'stardicto',
'stardictionaria',
'stardictionary',
'stardict']
['stardict',
'stardicto',
'stardictionary',
'stardictionaria',
'stardictionaries']
seurch1()
and seurch2()
are two functions that do exactly the same thing.
They are generator functions because of the presence of the keyword yield
instead of return
in them.
They act as iterators: they yield an element each time a call is done, as in:
for el in seurch2('stardict',wordlist):
print el
But list(seurch2('stardict',wordlist))
calls all the yielded elements in one shot and returns them in a list.
If you want to sort in alphabetical order, simply do:
sorted( seurch2('stardict',wordlist) )
because the elements are then sorted on the basis of their string value, and
print 'bc' < 'ba'
# False
print 'bc' < 'bda'
# True
print 'bcxyzterry' < 'bda'
# True
Upvotes: 1