Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could do it with the <code>struct</code> module. Here's a simple example based on the file formatting information you mentioned in a comment:</p> <pre><code>import struct def read_complex_array(filename, M, N): row_fmt = '={}h'.format(N) # "=" prefix means integers in native byte-order row_len = struct.calcsize(row_fmt) result = [] with open(filename, "rb" ) as input: for col in xrange(M): reals = struct.unpack(row_fmt, input.read(row_len)) imags = struct.unpack(row_fmt, input.read(row_len)) cmplx = [complex(r,i) for r,i in zip(reals, imags)] result.append(cmplx) return result </code></pre> <p>This will return a list of complex-number lists, as can be seen in this output from a trivial test I ran:</p> <pre><code>[ [ 0.0+ 1.0j 1.0+ 2.0j 2.0+ 3.0j 3.0+ 4.0j], [256.0+257.0j 257.0+258.0j 258.0+259.0j 259.0+260.0j], [512.0+513.0j 513.0+514.0j 514.0+515.0j 515.0+516.0j] ] </code></pre> <p>Both the real and imaginary parts of complex numbers in Python are usually represented as a pair of machine-level double precision floating point numbers.</p> <p>You could also use the <code>array</code> module. Here's the same thing using it:</p> <pre><code>import array def read_complex_array2(filename, M, N): result = [] with open(filename, "rb" ) as input: for col in xrange(M): reals = array.array('h') reals.fromfile(input, N) # reals.byteswap() # if necessary imags = array.array('h') imags.fromfile(input, N) # imags.byteswap() # if necessary cmplx = [complex(r,i) for r,i in zip(reals, imags)] result.append(cmplx) return result </code></pre> <p>As you can see, they're very similar, so it's not clear there's a big advantage to using one over the other. I suspect the <code>array</code> based version might be faster, but that would have to be determined by actually timing it with some real data to be able to say with any certainty.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload