IronPython: System.Array
When you start interop'ing with .NET in IronPython, sooner or later, you will find that you are in need of creating an array as argument. There are mainly 2 ways to create array objects:
- Array with type indexing (for one-dimensional array object only), and
- classic reflection API: Array.CreateInstance
System.Array indexing with a type creates a concrete array type, which can then take a collection of the element objects (or an enumerable) and form the array object. There are half dozen Array.CreateInstance overloads, which allow us to create one-dimensional empty array, also multi-dimensional/non-zero lower-bound arrays.
import System
array_int = System.Array[int]
print array_int # <type 'Array[int]'>
# list
print array_int([1, 2]) # System.Int32[](1, 2)
# tuple
print array_int((3, 4, 5)) # System.Int32[](3, 4, 5)
# xrange
print array_int(xrange(6,10)) # System.Int32[](6, 7, 8, 9)
# CLR List
print array_int(System.Collections.Generic.List[int]()) # System.Int32[]()
# one-dimensional array
a1 = System.Array.CreateInstance(int, 5)
for i in range(5): a1[i] = i * 10
print a1 # System.Int32[](0, 10, 20, 30, 40)
# two-dimensional array
a2 = System.Array.CreateInstance(float, 2, 2)
a2[1, 1] = 3.14
print a2 # System.Double[,](
# 0.0, 0.0
# 0.0, 3.14)
IronPython also supports some python list-like operation to the CLR array objects, such as indexing with slice, +, *, in...
a1 = array_int(range(5))
a2 = array_int([100])
# slice
print a1[1:-1] # System.Int32[](1, 2, 3)
# +
print a1 + a2 # System.Int32[](0, 1, 2, 3, 4, 100)
# *
print a1 * 2 # System.Int32[](0, 1, 2, 3, 4, 0, 1, 2, 3, 4)
# +, upcast the result to object[]
print a2 + System.Array[str]('py') # System.Object[](100, 'p', 'y')
# slice with step
print a1[1::2] # System.Int32[](1, 3)
# assignment
a1[1::2] = [11, 13]
print a1 # System.Int32[](0, 11, 2, 13, 4)
# in/__contains__
print 11 in a1 # True
Comments
- Anonymous
March 12, 2008
PingBack from http://msdnrss.thecoderblogs.com/2008/03/13/ironpython-systemarray/