首页 > 解决方案 > 将数字列表传递给 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

标签: python

解决方案


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])

推荐阅读