split function

bruno modulix onurb at xiludom.gro
Tue Aug 23 19:42:32 CEST 2005


Mohammed Altaj wrote:
> Dear all
> 
> Sorry , I confused between two things , what i said in the last e-mail i
> already managed to do using C code , But what i need to do using python
> is : my input data  :
> 
> 0 2 3 4
> 1 2 4
> 2 3
> 3 4
> 
> what i suppose to do is ,  using the first line and start searching
> number by number ,first i have 0 search in the rest of lines if there is
> 0 print out the all numbers except 0 , after that , start searching
> using the 2ed element in the first line which is 2 , in the 2ed line we
> have 1 , 4 . in the 3rd line we have 3 , in the 4th line we do not have
> 2. And so on for 3 and 4 , and also for the 2nd , 3rd lines , so the
> output should be
> 
> 0 2 1 4 3 3 2 4 4 1 2 3
> 1 2 3 4 3
> 2 3
> 3 4
> 
> And i managed to do this , but i did in the case of no space between
> numbers,when i am reading from file , like
> 0234
> 124
> 23
> 34
> 
> I want my code be able to deal with the space between numbers ,

"0 2 1 3\n".strip().replace(' ', '')
=> "0213"

> and this
> is my code again

(snip unreadable and overcomplicated implementation)

in_file = open('result.dat','r')
lines = [line.strip().replace(' ', '') for line in in_file]
in_file.close()

def find_relateds(target, lines):
    relateds = [target]
    for line in lines:
        if target in line:
            relateds.extend(list(line.replace(target, '')))
    return relateds

out_file=open('result2.dat','w')
for numline, line in enumerate(lines):
    buf = []
    for target in line:
        relateds = find_relateds(target, lines[numline+1:])
        buf.append(" ".join(relateds))
    buf = " ".join(buf)
    print buf
    out_file.write("%s\n" % buf)

out_file.close()

BTW, note that this won't work with numbers > 9. If you need to deal
with such a case, you can use str.split() to turn "10 21 32 43" into
["10", "21", "32", "43"]. Adapting the above code snippet to use this
scheme should be pretty straightforward.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list