When reading in data, Python gives me the following error:
TypeError: list indices must be integers or slices, not tuple with sys import in python
I use the following data.txt inputfile:
1.0 2.0 3.0
4.0 5.0 6.0
With the command !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?
coordinates is a list, and you are you are trying to pass in a tuple 0, 1 ,2
on the a=
line
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. 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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.