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

dpiehjr4  于 5个月前  发布在  Python
关注(0)|答案(1)|浏览(42)

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

import matplotlib.pyplot as plt
import numpy as np
import argparse  #added in later

data = np.array([[1,4], [2,2], [4,7], [6,3]])
x,y = data.T
print (data)

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

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


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

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


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

oprakyz7

oprakyz71#

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

import matplotlib.pyplot as plt
import numpy as np
import argparse
import ast  # added to parse the string representation of the list

# Define the command-line argument
parser = argparse.ArgumentParser()
parser.add_argument('data', type=str, help='List of lists representing data points')
args = parser.parse_args()

# Parse the string representation of the list into a Python list
data = ast.literal_eval(args.data)
data = np.array(data)

x, y = data.T
print(data)

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

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


它应该输出:

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

相关问题