Combining Lists and Tupels

Peter Abel p-abel at t-online.de
Thu May 22 14:55:09 EDT 2003


"Martin P" <martin_p at despammed.com> wrote in message news:<baierb$2cpp$1 at ID-108519.news.dfncis.de>...
> Hello,
> 
> for an exercise I have to programm a python script
> which sorts name, family names and addresses from a csv-File.
> The csv-File looks like this:
> 
> familyname;name;street;house-number;town-code;town
> 
> I did it like this:

Which can't work:

> 
> f=open("test.csv")
> 
> try:
>     while 1:

This is an endless loop. Could end in an overflow .. or not .. as Terry wrote

>             currentline=f.readline()
>             data=string.split(currentline, ";")
> 
>             address=data[2], data[3], data[4]

Doesn't work: You try to assign 3 values to a variable. The reverse is allowed.

>             list[i]=data[0], data[1], address

Doesn't work: See above. list hasn't been initialized.
              Assigning to list[i] fails, if the i'th element doesn't exist.
              list is a bad name for a variable because it's a Python keyword.

>             i+=1
Doesn't work: i haesn't been initialized.
> finally:
>     print "test error"
> 
> 
> But this does not work. I think my problem is with the combination of the
> list[i] and the Tupel address.

Python lets you combine nearly everything.

> 
> 
> 
> 
> Thanks a lot for help,
> 
> 
> bye,
> 
> Martin

The following would work:
>>> txt="""familyname;name;street;house-number;town-code;town
... Hoover;Peter;Kingslane;14;12345;Anyvillage
... Meyer;Joseph;Mainstreet;10;99999;Sometown"""
# Until here you have the same result, as if you would have read
# from a file, e.g.:
# txt=file('test.csv').read()
>>> lines=txt.split('\n')
>>> aList=[]
>>> for line in lines:
... 	fn,n,st,hn,tc,t=line.split(';')
... 	aList.append([fn,n,(st,hn,tc)])
#
# Test the results
#
>>> print '\n'.join(map(str,aList))
['familyname', 'name', ('street', 'house-number', 'town-code')]
['Hoover', 'Peter', ('Kingslane', '14', '12345')]
['Meyer', 'Joseph', ('Mainstreet', '10', '99999')]

Hope that helps.
Regards Peter




More information about the Python-list mailing list