Thread: Outout of array

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    5
    Rep Power
    0

    Outout of array


    I've few questions.
    1. How to generate float numbers in an array?
    I use something like that
    Code:
    import array
    import random
    a=array.array('i',(random.randint(-50,51) for i in xrange(10)));
    print a
    This gives integer [-50; 50], but how to get float, for example, [-1, 1], not [-1, 1)?
    2. How to output array in columns?
    For example, I have generated array and I want to make output in 3 columns, how can I do it?
    3. How to output array in rows?
    Same that with columns, but, for example, in 10 rows.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,996
    Rep Power
    481
    numpy handles arrays more elegantly than does plain old python. Look for the enthought python distribution, or scipy.org

    >>> random.random()
    0.95659562170489

    You might have to make lists of array to get "tables" using array. Yes, arrays don't support a "collection type".
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    620
    Rep Power
    65
    One way to do that:
    Code:
    ''' array_floats1.py
    create a Python array of 10 random floats between -1 and 1
    print the elements with different options
    '''
    
    # allows Python27 to use Python3 print() options
    from __future__ import print_function
    
    import array
    import random as rn
    
    arr = array.array('f',[rn.random()*rn.choice([-1,1]) for i in range(10)])
    
    # print 3 items max per row
    count = 1
    for item in arr:
        #print(count, count % 3)
        if count % 3 == 0:
            print("%10.6f" % item, end="\n")
        else:
            print("%10.6f" % item, end=" ")
        count += 1
    
    print("")
        
    print('-'*32)
    
    # print 1 item per row
    for item in arr:
        print("%10.6f" % item)
    
    ''' potential output -->
     -0.357831  -0.926154   0.836476
      0.317901  -0.845858  -0.940639
      0.895811   0.133088   0.346653
      0.618086 
    --------------------------------
     -0.357831
     -0.926154
      0.836476
      0.317901
     -0.845858
     -0.940639
      0.895811
      0.133088
      0.346653
      0.618086
    '''
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo