c_type python添加值

问题描述 投票:-1回答:1

我试图将一些值添加到现有变量。我是Python的新手。我正在使用ctype变量。这是我的代码不起作用。

rgdSamples = (c_double * 100)()
fSamples = (c_double * 1000)()
for i in range(10)
   fSamples += rgdSamples;

有什么建议?

python ctypes
1个回答
-1
投票

根据您的代码段中的数值,我假设fSamples应该是一个2D数组(10行,100列)的双精度数。 不清楚为什么[Python 3]: ctypes - A foreign function library for Python是首选而不是Python列表,但这里是一个例子(出于显示目的,数组要小得多)。

code.朋友:

#!/usr/bin/env python3

import sys
import ctypes


COLS = 10  # Change it to 100
ROWS = 5  # change it to 10
DoubleArr1D = ctypes.c_double * COLS
DoubleArr2D = (ctypes.c_double * COLS) * ROWS  # Parentheses present for clarity only


def print_matrix(matrix, text=None):  # This function isn't very Pythonic, but keeping it like this for clarity
    if text is not None:
        print(text)
    for row in matrix:
        for element in row:
            print("{:6.2f}  ".format(element), end="")
        print()
    print()


def main():
    mat = DoubleArr2D()  # Initialize matrix with 0s
    arr = DoubleArr1D(*range(1, COLS + 1))  # Initialize array with numbers 1..COLS
    print_matrix(mat, text="Initial matrix:")

    for row_idx in range(ROWS):
        for col_idx in range(COLS):
            mat[row_idx][col_idx] += arr[col_idx] * (row_idx + 1)  # Add the values from array (multiplied by a factor) to the current row

    print_matrix(mat, text="Final matrix:")


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()
    print("Done.")

输出:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055494830]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Initial matrix:
  0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
  0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
  0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
  0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
  0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00

Final matrix:
  1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00   10.00
  2.00    4.00    6.00    8.00   10.00   12.00   14.00   16.00   18.00   20.00
  3.00    6.00    9.00   12.00   15.00   18.00   21.00   24.00   27.00   30.00
  4.00    8.00   12.00   16.00   20.00   24.00   28.00   32.00   36.00   40.00
  5.00   10.00   15.00   20.00   25.00   30.00   35.00   40.00   45.00   50.00

Done.
© www.soinside.com 2019 - 2024. All rights reserved.