Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

python 3.x - The task is to convert strings to floats, but my files are still strings. Why?

Here I'm trying to convert few numbers inside a list read from a file into float format, but my output comes still as a string format. Where is the problem?

table = [] 
fileName = input("Enter the name of the file: ")
readFile = open(fileName)
lines = readFile.readlines() 
    
for line in lines: 
    line = line.split()
    for item in line: 
        item = float(item)
    table.append(item)

print(table)

Here is a screenshot of my code :

snapshot of code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should append the item that is a float(stored in the variable Item) and not the string version(stored in the variable line) inside the loop so each item is added as the loop iterates through the items.I also use the split() function to add every three numbers into another nested list

Here is the fixed code:

table = []
readFile = open(filename)
lines = readFile.readlines()
for i  in lines:
    for line in i.split():
        items = float(lines)
        table = [[items]]

print(table)

OR:

readFile = open(filename)
lines = readFile.readlines()
table=[([items] for line in i.split) for i in lines]

print(table)

Output:

[[2.0,7.0,6.0],[9.0,5.0,1.0],[4.0,3.0,8.0]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...