用户的矢量输入-python

时间:2019-03-02 13:09:17

标签: python vector

我正在尝试使用输入函数获取向量以进行数学运算。下面是我正在使用的代码。

任何指针都会帮助

谢谢, Prashant

vector1=input()

(1,2,3),(4,5,6),(7,8,9)

vector1=np.array(vectors.split(','),dtype=np.int16)


Error:
line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-109-6cf21e5e043d>", line 1, in <module>
    vector1=np.array(vectors.split(','),dtype=np.int16)
ValueError: invalid literal for int() with base 10: "('(1"

1 个答案:

答案 0 :(得分:0)

regular expressions的帮助下,您可以执行以下操作:

import numpy as np
import re

user_input = "(1,2,3),(4,5,6),(7,8,9)"

# Convert user-provided string to nested list
x = re.findall(r"\((\d+(?:,\d+)*)\)", user_input)
x = [part.split(',') for part in x]

# Create 2D numpy array from nested list
arr = np.array(x, dtype=int)

print(arr)
# Output:
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]