我可以使用numpy将矩阵作为python中的命令行输入传递吗? [英] Can I pass a matrix as command line input in python with numpy?

查看:215
本文介绍了我可以使用numpy将矩阵作为python中的命令行输入传递吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的程序,该程序使用numpy为我提供了康威生活游戏的下一步. 现在,我所能做的就是更改程序中的1和0:-

I'm working on a simple program that gives me the next step of Conway's game of life, using numpy. Right now, all I can do is alter the ones and zeros in the program :-

seed = np.array([[0,0,0,0],[0,1,1,0],[0,1,1,1],[0,0,0,0]])  
print(nextStep(seed))

但是我希望能够在命令行中传递初始数组.我有什么办法可以做到这一点?

But I'd like to be able to pass the initial array in command line. Any way I can do this ?

推荐答案

您想要的基本上是将文本转换为结构化数据(此处为numpy数组).因为手动执行操作(例如拆分字符串或使用eval)充满了错误和安全漏洞,所以我建议使用一个为您进行解析的库.

What you want is basically to convert text into structured data (numpy array here). Because doing so manually (like splitting strings or using eval) is fraught with bugs and security vulnerabilities, I recommend using a library that does the parsing for you.

在这里,我认为json是最自然的格式.用法示例

Here I think json is the most natural format. Example usage

import json
import numpy
import sys

data = numpy.array(json.loads(sys.argv[1]))
# do you calculation

现在您可以在命令行上运行

Now you can run on the command line

python myscript.py '[[0,0,0,0],[0,1,1,0],[0,1,1,1],[0,0,0,0]]'

这篇关于我可以使用numpy将矩阵作为python中的命令行输入传递吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆