numpy 如何将2d参数列表传递给Python?

dpiehjr4  于 2024-01-08  发布在  Python
关注(0)|答案(1)|浏览(137)

用例是我有一个x,y坐标列表,我在matplotlib图中显示。我硬编码的值如下,让它工作。
我使用的代码是:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import argparse #added in later
  4. data = np.array([[1,4], [2,2], [4,7], [6,3]])
  5. x,y = data.T
  6. print (data)

字符串
这是可行的,所以我尝试添加argparse,以使其具有n(参数)并取出硬编码值:

  1. parser = argparse.ArgumentParser()
  2. args = parser.parse_args()


在传入参数后,下面的许多变体:

  1. python multi_point.py ([[1,4], [2,2], [4,7], [6,3]])


我一直得到关于这个结构作为一个“命名空间”而不是一个可迭代的错误?
然而,我不知道是不是这个库不对,或者我的终端语法不对,或者别的什么?顺便说一句,我使用VSCode作为我的IDE,并在终端上运行它。
你觉得我哪里做错了吗?

oprakyz7

oprakyz71#

你可以使用ast来解析python程序中的字符串:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import argparse
  4. import ast # added to parse the string representation of the list
  5. # Define the command-line argument
  6. parser = argparse.ArgumentParser()
  7. parser.add_argument('data', type=str, help='List of lists representing data points')
  8. args = parser.parse_args()
  9. # Parse the string representation of the list into a Python list
  10. data = ast.literal_eval(args.data)
  11. data = np.array(data)
  12. x, y = data.T
  13. print(data)

字符串
由于空格的原因,你仍然需要用双引号将参数括起来:

  1. python test.py "[[1,4], [2,2], [4,7], [6,3]]"


它应该输出:

  1. [[1 4]
  2. [2 2]
  3. [4 7]
  4. [6 3]]

展开查看全部

相关问题