split function
bruno modulix
onurb at xiludom.gro
Tue Aug 23 12:58:06 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
Remove them ?
> This is my code
Your code does not seems to work as expected. I get:
0 3 4 2 1 3
0 4 3 2
0 4 1
1 4 2 3
1 4
2 3
3
>
> def belong_to(x,a):
> c=-1
> for i in range(len(a)-1):
> if x==int(a[i]):
> c=i
> return c
def belong_to(x, line):
for i, c in enumerate(line.strip()):
if x == int(c):
return i
return -1
def belong_to(x, line):
return line.find(str(x))
belong_to = lambda x, line: line.find(str(x))
Now, is it useful to define a function for such a trivial test ?
> def list_belong(x,a): # This function to check if this line
> c=-1 # line has been searched
> before or not
> for i in range(len(a)):
> if a[i]==x:
> c=1
> break
> return c
def list_belong(line, lines):
return line in lines
... is it really useful to define a function for such a trivial test ?
> x=0
> occur=[]
>
> in_file=open('data.dat','r')
> out_file=open('result.dat','w')
> fileList = in_file.readlines()
> for k in fileList:
> v=k
> occur.append(k)
> n=len(v)-1
> for i in range(n):
> temp=int(v[i])
> print temp,
> out_file.write(str(temp))
> for line in fileList:
> if v!=line:
> if list_belong(line,occur)!=1:
> if belong_to(temp,line) != -1:
> j=belong_to(temp,line)
> for i in range(len(line)-1):
> if i!=j:
> print line[i],
> out_file.write(line[i])
ouch :(
>
> print
> out_file.write("\n")
>
> out_file.close()
> in_file.close()
>
May I suggest a much more simple version that conform to your specs and
solves the space problem ?
from itertools import groupby
in_file=open('data.dat','r')
# strip EOLs and get rid of whitespaces
lines = [line.strip().replace(' ', '') for line in_file.readlines()]
in_file.close()
out_file=open('result.dat','w')
# group lines by first char
for key, groups in groupby(lines, lambda line: line[0]):
buf = "%s %s" % (key, " ".join([group[1] for group in groups]))
print buf
out_file.write("%s\n" % buf)
out_file.close()
Python is meant to make your life easier...
--
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