String to int newbie question
Anton Vredegoor
anton at vredegoor.doge.nl
Mon Mar 24 07:00:38 EST 2003
Luka Milkovic <Luka.Milkovic at public_MAKNIME_.srce.hr> wrote:
>Ok, I proabably haven't been clear enough. Here is what I really want to
>do: I have a list of strings ( the content of strings are actually
>numbers ), for example I have the following list: ['4312', '7599',
>'0724', '0003']. The things I need to do is to change the strings inside
>the list to integers and then write the list to a file ( I know how to do
Well, you didn't specify which integers correspond to which strings
:-)
>the latter:). The problem is, if I change it with
>int(my_string_inside_the_list) I won't get the same numbers, and I need
>to have the content of the string and integer the same. So, after the
>conversion of that list, what I want to have is: [4312, 7599, 0724, 0003]
>and NOT [4312, 7599, 724, 3].
If you don't mind the strings corresponding to unusual integers
there's another way to do it.
Anton.
class sequencer:
def __init__(self,items):
#initialize an instance with the list of possible items
self.items = items
self.base = len(items)
def __getitem__(self,n):
# return the list of items with rank n
result,todo = [], n
while todo >= 0:
todo,i = self.splitat(0,todo)
result.append(self.items[i])
result.reverse()
return result
def rank(self,L):
#compute the rank of a list of items
r = self.items.index(L[0])
for x in L[1:]:
i = self.items.index(x)
r = self.concat(r,i)
return r
def concat(self,a,b):
# compute the number for a + b concatenated
i,j = 0,1
while i <= b:
j = j * self.base
i = i + j
return j*(a+1)+b
def splitat(self,pos,x):
#compute the numbers for x splitted at position pos
i,j = 0,1
for k in range(pos+1):
j = j * self.base
i = i + j
a = (x-i)/j
b = x-j*(a+1)
return a,b
def test():
seq = sequencer('0123456789')
ss = ['4312','7599','0724','0003']
ints,sstest = [],[]
for s in ss:
ints.append(seq.rank(s))
print ints
for i in ints:
sstest.append(''.join(seq[i]))
print sstest
assert ss == sstest
if __name__=='__main__':
test()
More information about the Python-list
mailing list