[英]TypeError: list indices must be integers or slices, not tuple with sys import in python
When reading in data, Python gives me the following error:在读入数据时,Python 给了我以下错误:
TypeError: list indices must be integers or slices, not tuple with sys import in python
类型错误:列表索引必须是整数或切片,而不是在 python 中使用 sys 导入的元组
I use the following data.txt inputfile:我使用以下 data.txt 输入文件:
1.0 2.0 3.0
4.0 5.0 6.0
With the command !python file_name data.txt import sys使用命令 !python file_name data.txt import sys
fp = open(sys.argv[1],"r+")
coordinates = fp.readlines()
fp.close()
import numpy
a = numpy.array(coordinates[0, 1, 2])
b = numpy.array(coordinates[3, 4, 5])
dist_unround=numpy.linalg.norm(a-b)
dist_round=round(dist_unround, 2)
energy_unround=0.5*2*((dist_unround-3.0)**2)
energy_round=round(energy_unround,2)
print("dist \t energy")
print(dist_round,"\t" ,energy_round)
I try to calculate a vector from a random input textfile.我尝试从随机输入文本文件中计算向量。 Is there something wrong with my numpy.array code?
我的 numpy.array 代码有问题吗?
coordinates is a list, and you are you are trying to pass in a tuple 0, 1 ,2
on the a=
line坐标是一个列表,并且您正试图在
a=
行上传递元组0, 1 ,2
To use method correctly, replace要正确使用方法,请更换
a = numpy.array(coordinates[0, 1, 2])
b = numpy.array(coordinates[3, 4, 5])
with和
a = numpy.array(coordinates[0].split())
b = numpy.array(coordinates[1].split())
Note that readlines
returns a list of strings.请注意,
readlines
返回一个字符串列表。 Call index 0 on that list ( coordinates[0]
) to get the first set (row) of values, then use .split()
method on that string to make them a list of strings that were separated by spaces.调用该列表(
coordinates[0]
)上的索引 0 以获取第一组(行)值,然后对该字符串使用.split()
方法使它们成为由空格分隔的字符串列表。
You may want to cast those as floats or ints while you are at it.您可能希望在使用时将它们转换为浮点数或整数。 Could do that with a list comprehension if you wanted
如果你愿意,可以用列表理解来做到这一点
a = numpy.array([int(x) for x in coordinates[0].split()])
b = numpy.array([int(x) for x in coordinates[1].split()])
From the little details you gave, I guess, this is what you were looking for-从你提供的小细节来看,我猜这就是你要找的——
arr=[]
with open("data.txt") as f:
for line in f:
a=list(line.split(" "))
for element in a:
arr.append(float(element.rstrip()))
print(arr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.