split function

rafi rafi at free.fr
Mon Aug 22 16:53:40 EDT 2005


Mohammed Altaj wrote:
> Dear All
> 
> What i want to do is , my input is like
> 0 2
> 0 3
> 0 4
> 1 2
> 1 4
> 2 3
> 3 4
> 
> I am comparing and put the number in group , like ,the first three lines
> , all has zero as first input for each line, so the out put should look
> like
> 0 2 3 4
> and so on
> 1 2 4
> 2 3
> 3 4
> 
> I managed to do what i need , but i did in this case , there is no space
> between numbers , like
> 02
> 03
> 04
> 12
> 14
> 23
> 34
> 
> so , how can i do this with spaces between numbers

with a two pass processing (one for building the output, one for its 
printing), using a dict to make lists for each index (everything is 
treated as strings as you do not compare nor compute them)

results = dict ()

input = file ('input.dat')

for line in input:
     idx, value = line.split ()
     if idx in results:
         results [idx] .append (value)
     else:
         results [idx] = [value]

input.close ()

output = open ('output.dat', 'w')

for idx, values in results.items ():
     output.write ('%s %s\n' % (idx, ' '.join (values)))

output.close ()

you can define two function, in case of your output may vary in the future.

 > [snip your code]

8 levels of indentation seems really to much for a good ppiece of code 
from my point of view.

my 2 cents


-- 
rafi

	"Imagination is more important than knowledge."
	                            (Albert Einstein)



More information about the Python-list mailing list