python - 将数字列表传递给 Python 脚本
问题描述
我正在尝试将一列数字传递给 Python 脚本,然后转换为numpy
数组。
输入.txt
42
42.4
43.5153
44
重击代码
python script.py ${input}
Python 脚本
#!/usr/bin/env python3
import sys
import numpy
in = sys.argv[1]
in_out = np.array([float(in)])
print "Inputs:" in_out
sys.exit()
Python 错误
Traceback (most recent call last):
File "script.py", line 8, in <module>
in_out = np.array([float(in)])
ValueError: invalid literal for float(): 42
解决方案
import numpy as np
with open('input.txt') as input_file:
data = np.array([float(line.strip()) for line in input_file])
您需要将所有值转换为浮点数,以便 numpy 仅在数组中存储一种数据类型。
如果要将文件作为参数提供,可以执行以下操作:
import numpy as np
import sys
file_name = sys.argv[1]
with open(file_name) as input_file:
data = np.array([float(line.strip()) for line in input_file])
推荐阅读
- python - 如何使用 Tkinter GUI 正确实现多线程?
- python - 移动平均条件到其他列
- javascript - javascript代码中变量php的值
- android - 使用 Request 添加方法时,Kotlin 使用 OkHttp 编译错误
- java - 使用 Scala 或 Java 将 .p12 转换为 .pem 以在 AWS SNS 中注册
- squarespace - 如何为 Squarespace Commerce API 查找产品变体的变体 ID
- apache-spark - 带有 USING 和 PARTITIONED BY 子句的 spark hive 创建表的有效语法是什么?
- wsdl - 如何使用 Zeep 修复 WSDL 请求中的“无效标签名称”?
- regex - 捕获电子邮件正文的第 n 个 url 出现
- database - 如何在 cassandra 中将数据从一个键空间复制/迁移到另一个键空间?