Re: How to initialize an array with a large number of members ?

2008-12-31 Thread MRAB

da...@bag.python.org wrote:

Thanks to those who have helped a beginner in
Python. Using version 3.0

# script23
from array import array
 see failed initialization attempts  below 

tally = array('H',for i in range(75) : [0])

tally = array('H',[for i in range(75) : 0])

tally = array('H',range(75) : [0])

tally = array('H',range(75) [0])

  Above give either Syntax error or TypeError

   All examples of sequences in docs show only
   a few members being initialized. Array doc 
   says an iterator can be used, but doen't show
   how.  What would you do for a 2 dimensional 
   array ?  Incorporate c code ?

   The online docs are clearly insufficient for a
   novice.  Have ordered Summerfields new book.


 # With a list
 tally = array('H', [0] * 75)

 # With a generator
 tally = array('H', (0 for i in range(75)))
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to initialize an array with a large number of members ?

2008-12-31 Thread bearophileHUGS
MRAB:
   # With a list
   tally = array('H', [0] * 75)
  
   # With a generator
   tally = array('H', (0 for i in range(75)))

Time ago we have had a long discussion about this, the right way is:

tally = array(someformat, [0]) * 75

(If you need to initialize it to something that isn't constant then
you may have to do something different).

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to initialize an array with a large number of members ?

2008-12-31 Thread Scott David Daniels

David Lemper wrote:

... Python. Using version 3.0
# script23
from array import array
 see failed initialization attempts  below 
tally = array('H',for i in range(75) : [0])
tally = array('H',[for i in range(75) : 0])
tally = array('H',range(75) : [0])
tally = array('H',range(75) [0])
  Above give either Syntax error or TypeError

 All examples of sequences in docs show only a few members
 being initialized. Array doc says an iterator can be used,
but doesn't show how. 

First, [1,2,3] is iterable.  You could look up iterators or
generators or list comprehension, but since it's the holidays:
import array
tally = array.array('H', (0 for i in range(75)))# a generator
tally = array.array('H', [0 for i in range(75)])# list comprehension

What would you do for a 2 dimensional array ?  

You'll have to wait for numpy for the most general 2-D,
but for list-of-array:
square = [array.array('H', (i * 100 + j for j in range(75)))
  for i in range(75)]
square[4][8]
--
http://mail.python.org/mailman/listinfo/python-list