A problem with list
Tim Henderson
tim.tadh at gmail.com
Mon Dec 13 23:40:36 EST 2004
Hi
There are many different ways to solve the problem that you are having.
The easiest if you are planning on only dealing with strings or a
predictable data structure would be to do something like this:
Code:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Pre: Pass in a string and the character you want it tokenized by
#Post: Returns a list of all the tokens
def tokenizer(str, chr=' '): #heres a useful tool just like
StringTokenizer feature in Java
if chr != '': chr = chr[0]
else: chr = ' '
x = ""
tokens = [""]
z = 0
for x in str:
if x != chr:
tokens[z] = tokens[z] + x
else:
z = z + 1
tokens.append("")
return tokens
list = ['abc', 'def', 'xyz']
str = ''
for x in list:
str+=list+'.' #note this is a delimiter could be anything, if you
wanted to you could re-implement the above function to work with
delimiters of any length not just length 1
#save the str
#load str a loadedStr
loadedList = tokenizer(loadedStr, '.')
#loadedList = ['abc', 'def', 'xyz']
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
that is one way too solve your problem
another is to use some sort of real database structure, for simplicity,
you could use XML
example xml structure:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<list-element>
<date_type>float</data_type>
<value>3.14</value>
<element_number>0</element_number>
</list-element>
<list-element>
<date_type>int</data_type>
<value>3</value>
<element_number>1</element_number>
</list-element>
<list-element>
<date_type>string</data_type>
<value>Hi i am a string</value>
<element_number>2</element_number>
</list-element>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The first way to solve your problem is quick dirty and efficient. The
XML version is highly scalable but requires a lot more code to
implement. As mentioned before there are a number of other solutions to
the same problem
---
Cheers
Tim Henderson
original message:
----
>The following code
>##############
>import string
>MyList=['abc','def']
>for i in MyList:
>print i
>###############
>
>works as I expect that is I get
>abc
>def
>
>but when I have Mylist in a file and I read it from the file it does
>not work as I expect.
>#########
>import string
>ff=open('C:\\Robotp\\MyFile.txt','r') # read MyList from a file
>MyList=ff.read()
>for i in MyList:
>print i
>###########
>I will get
>[
>'
>a
>b
>c
>'
>,
>'
>d
>e
>f
>'
>]
>
>where my MyFile.txt looks like this:
>['abc','def']
>
>Where is a problem?
>Thanks for help
>Lad
>
More information about the Python-list
mailing list