Array design question
Harvey Thomas
hst at empolis.co.uk
Thu May 29 11:41:23 EDT 2003
Peter Slizik wrote:
>
> Hi pythoners,
>
> after changing some messages in the 'Two dimensional
> array' thread,
> the discussion turned into somewhat philosophical debate on the way
> Python works with arrays.
>
> I've been working with languages like PHP and Perl for some time.
> Things so simple in PHP looks very difficult in Python (at
> least for me).
>
> Simple PHP code
>
> a[1] = 'aaa'
> a[2] = 'bbb'
> a[3] = 'ccc'
>
> will in Python read
>
> a.append('aaa')
> a.append('bbb')
> a.append('ccc')
>
> which is in my opinion uglier than PHP code.
>
> I just don't understand, why Python doesn't allow to exceed array
> boundaries. PHP and Perl would resize the array in this case.
>
> Let's have a simple example. Suppose we have the file in format
> 7 "Text 1"
> 5 "Text 2"
> 3 "Text 3"
> ...
> ...
>
> Our task is to read the content of the file into the array.
>
> Simple PHP code
>
> while( !eof() ) {
> line = readline();
> (number, text) = split(line);
> array[number] = text;
> }
>
> seems untranslatable into Python. The first attempt to store
> an object
> with index 7 into array before other 6 objects are stored there, will
> cause an exception. But the numbers in the input file aren't in any
> special order.
>
> Is there any reason why Python designers chose this concept?
> Wouldn't it
> be more convenient to have PHP-like arrays in Python too?
>
> -- Peter
I think part of your problem is that you are comparing a PHP array with a Python list, whereas a PHP array is much more akin to a python dict. So an equivalent of your PHP code in Python is:
array = {}
for aline in afile:
number, text = split(aline)
array[number] = text
which bears more than a passing resemblance to your PHP code.
_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.
More information about the Python-list
mailing list