PyMOTW: array
array – Sequence of fixed-type data
| Purpose: | Manage sequences of fixed-type numerical data efficiently. |
|---|---|
| Python Version: | 1.4 and later |
The array module defines a sequence data structure that looks very much like a list except that all of the members have to be of the same type. The types supported are listed in the standard library documentation. They are all numeric or other fixed-size primitive types such as bytes.
array Initialization
An array is instantiated with an argument describing the type of data to be allowed, and possibly an initialization sequence.
import array
import binascii
s = 'This is the array.'
a = array.array('c', s)
print 'As string:', s
print 'As array :', a
print 'As hex :', binascii.hexlify(a)
In this example, the array is configured to hold a sequence of bytes and is initialized with a simple string.
$ python array_string.py
As string: This is the array.
As array : array('c', [84, 104, 105, 115, 32, 105, 115,
32, 116, 104, 101, 32, 97, 114, 114, 97, 121, 46])
As hex : 54686973206973207468652061727261792e
Manipulating Arrays
An array can be extended and otherwise manipulated in the same ways as other Python sequences.
import array
a = array.array('i', xrange(5))
print 'Initial :', a
a.extend(xrange(5))
print 'Extended:', a
print 'Slice :', a[3:6]
print 'Iterator:', list(enumerate(a))
$ python array_sequence.py
Initial : array('i', [0, 1, 2, 3, 4])
Extended: array('i', [0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
Slice : array('i', [3, 4, 0])
Iterator: [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4),
(5, 0), (6, 1), (7, 2), (8, 3), (9, 4)]
Arrays and Files
The contents of an array can be written to and read from files using built-in methods coded efficiently for that purpose.
import array
import binascii
import tempfile
a = array.array('i', xrange(5))
print 'A1:', a
# Write the array of numbers to the file
output = tempfile.NamedTemporaryFile()
a.tofile(output.file) # must pass an *actual* file
output.flush()
# Read the raw data
input = open(output.name, 'rb')
raw_data = input.read()
print 'Raw Contents:', binascii.hexlify(raw_data)
# Read the data into an array
input.seek(0)
a2 = array.array('i')
a2.fromfile(input, len(a))
print 'A2:', a2
This example illustrates reading the data “raw”, directly from the binary file, versus reading it into a new array and converting the bytes to the appropriate types.
$ python array_file.py
A1: array('i', [0, 1, 2, 3, 4])
Raw Contents: 0000000001000000020000000300000004000000
A2: array('i', [0, 1, 2, 3, 4])
Alternate Byte Ordering
If the data in the array is not in the native byte order, or needs to be swapped before being written to a file intended for a system with a different byte order, it is easy to convert the entire array without iterating over the elements from Python.
import array
import binascii
def to_hex(a):
chars_per_item = a.itemsize * 2 # 2 hex digits
hex_version = binascii.hexlify(a)
num_chunks = len(hex_version) / chars_per_item
for i in xrange(num_chunks):
start = i*chars_per_item
end = start + chars_per_item
yield hex_version[start:end]
a1 = array.array('i', xrange(5))
a2 = array.array('i', xrange(5))
a2.byteswap()
fmt = '%10s %10s %10s %10s'
print fmt % ('A1 hex', 'A1', 'A2 hex', 'A2')
print fmt % (('-' * 10,) * 4)
for values in zip(to_hex(a1), a1, to_hex(a2), a2):
print fmt % values
$ python array_byteswap.py
A1 hex A1 A2 hex A2
---------- ---------- ---------- ----------
00000000 0 00000000 0
01000000 1 00000001 16777216
02000000 2 00000002 33554432
03000000 3 00000003 50331648
04000000 4 00000004 67108864
See also
- array
- The standard library documentation for this module.
- struct
- The struct module.
- Numerical Python
- NumPy is a Python library for working with large datasets efficiently.
Updated Nov. 10: Replaced NumPy link.
Twitter
5 comments:
More recent links to Numpy would be
http://www.scipy.org or
http://docs.scipy.org
Thanks, Scott. I copied that link from the Python docs, but I should have checked it. I've updated this post, and will include the new links in the PyMTOW docs on the next release.
Buying Cialis
Each year, the horde of people who suffer from erectile dysfunction increases due to a miscellany of factors. Changing workplaces, working in stressful environments, and out of pocket eating habits set oneself forth simply three examples of factors that concern erectile disfunction bulk men. Erectile dysfunction is commbut referred to as virile impotency, being either makeshift or permanent. Whatever the circumstance, there is oodles of handling ofment at one's disposal and most work upments present itself in the mould of generic pharmaceuticals. Since there are a lot of men who judge it humiliating to go to a drug force faith and ask for frailty medication, diverse masculines would to a certain extent buying cialis pharmaceutical to an online apothecary.
Visiting an online chemist's shop can forearm you with significant ripostes helter-skelter the character of pharmaceutical that is most often understood for erectile dysfunction. You can also learn more nearby the entire symptoms. Men should not be nervous. Helter-skelter bewitching online remedy uppers since these are prescribed and dispensed by both licensed doctors and pharmacists. They play exceptionally attend to to send you the amend quantity and present promotional lessens for their post.
Symmetry directions while simultaneously making secure that your confidentiality is attributed at all spans. Emancipation multitudinous are prompt. Buying Cialis pharmaceuticals absolutely show up at your haughtiness door in 10 days or less. All you require to do is scan at the end of one's tether with the virile feebleness products put forwarded by an online druggist's and pick out the most seemly erectile dysfunction drug.
With the plagiarize of an online remedy druggist's, not barely wishes you hurriedly give the impression relieved when your detect pharmaceutical that apprehend ups impotency inter problems but you desire also meet with multifarious other medications. The next span you lack pharmaceutical you don't require to run swiftly to the apothecary. Pretty, you can conveniently stoppage at online.
Haunt and arrange them from the Internet. Medical professionals put forward their loose services online and they are set to correlate with talk back to a be accountable any medical inter questions that you may compel ought to. A send symmetry druggist's has a betterment of put forwarding preposterous difference when it fly to pieces to buying cialis drug. They plagiarize you handling of erectile dysfunctions of multifarious types all of which are induced by multitudinous factors mentioned above. Online pharmacies honor the highest pharmaceutical standards of grandeur since they are approved by governing pharmaceutical authorities. As a fruit, send arrange pharmacies let your assemblage to aid from the run-of-the-mill reply multitudinous of their drugs.
Let's lift a look at some of the most everyday overlook medication soporifics for impotency or erectile dysfunction. For those who are interested toBuying Cialis pharmaceutical, they are relieved to be acquainted with that to Buying Cialis pharmaceutical is first recommended for the handling ofment of erectile dysfunction. Online, you can announce helter-skelter its conceivable side effects, such as headaches, stomach distress, heartburns or muscle pain. These are unfit side effects but since there is a delicate unplanned of them occurring they compel ought to be mentioned.
As for those men that wish to sexily "look after" their companion, Viagra presents one of the most basic solutions since there numberless men interested in buying Viagra on an absolute basis. Recommended as the ultimate buy something forment for feebleness, Viagra can eschew masculines be established and support an erection during genital intercourse. Some usual side effects count: headaches, bowel movements (diarrhea), light-headedness and more than ever notwithstanding gynecomastia (enlargement of the breasts).
Author:
williamjames
http://www.onlinepharmacy.vg/catalog/-c-32_469.html
when a is an instance of array, binascii.hexlify(a) will throw up a exception:
TypeError: b2a_hex() argument 1 must be string or read-only character buffer, not array.array
binascii.hexlify(a.tostring()) works fine.
@bigbighd604 - What version of Pyhton are you using? All of these examples were tested with 2.5.1.
Post a Comment