[Tutor] Tutor] string list in alphabetical!
Alan Gauld
alan.gauld at btinternet.com
Tue Oct 22 00:58:39 CEST 2013
On 21/10/13 17:16, Siva Cn wrote:
> Hi Sammy,
>
> Try this this may help you !
Siva,
the list policy is not to provide full solutions for homework type
questions. It's better to provide some hints and let the OP
figure it out for him/her self.
That having been said there are a few issues with the code below...
> ----------------------------------------------------------------------------------
> def sort_file1_to_file2(file1, file2):
> """."""
A docstring with a dot is pretty useless, unless there's
some Python magic going on that I'm unaware of
> input_content = []
This is not needed since you initialise it below
> with open(file1, 'r') as fp:
> input_content = fp.read()
> input_content = input_content.splitlines()
It would be easier to use readlines to get each line in
a list. And given we know there are only 26 lines memory
usage is not an issue.
> _dict = {ele[0].lower(): ele for ele in input_content}
>
> out_content = "\n".join([_dict[chr(idx)]
> for idx in range(97, 123)
> if chr(idx) in _dict])
And this is way more complicated than need be. We know the lines start
with unique letters of the alphabet so we can just use the built in
sort() method or sorted() function to get
outcontent = "".join(sorted(input_content)) # readlines preserves \n?
If the first letters are mixed case there would need a slight tweak to
account for that but there is no suggestion from the OP that that
is an issue.
> with open(file2, 'w') as fp:
> fp.write(out_content)
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list