easy but difficult
Paul McGuire
ptmcg at austin.rr.com
Tue Oct 16 08:32:06 EDT 2007
On Oct 16, 5:46 am, "Amit Khemka" <khemkaa... at gmail.com> wrote:
> On 10/16/07, Beema shafreen <beema.shafr... at gmail.com> wrote:
>
>
>
>
>
> > hi everybody,
> > I have a file separated by hash:
> > as shown below,
> > file:
> > A#1
> > B#2
> > A#2
> > A#3
> > B#3
>
> > I need the result like this:
> > A 1#2#3
> > B 2#3
>
> > how will generate the result like this from the above file
> > can somebody tell me what i have to do......
> > My code:
> > fh =open('abc_file','r')
> > for line in fh.readlines():
> > data = line.strip().split('#')
> > for data[0] in line
> > print line
>
> > I tried but i donot know how to create 1#2#3 in a single line
> > regards
> > shafreen
>
> While looping over the file you may store alphabets as key in a
> dictionary and numbers as values.
>
> for example:
>
> <code_untested>
> d = {}
> for line in open('abc_file'):
> data = line.strip().split('#')
> # add the numbers to the 'alphabet' key as a list
> d[data[0]] = d.get(data[0], []) + [data[1]]
> <code_untested>
>
> Now you can just iterate over the dictionary and write it into a file
>
> Cheers,
>
> --
> --
> Amit Khemka- Hide quoted text -
>
> - Show quoted text -
Another technique that helps improve script readability is to assign
the results of the split into separate variables, instead of just a
list. This way you can refer to the items with meaningful names
instead of less readable index-into-the-list references:
for line in open('abc_file'):
datakey,datavalue = line.strip().split('#')
# add the numbers to the 'alphabet' key as a list
d[datakey] = d.get(datakey, []) + [datavalue]
-- Paul
More information about the Python-list
mailing list