Reading numbers in python string

Asked 2 years ago, Updated 2 years ago, 15 views

Hi, everyone. Using Python to read the file containing the numerical values as shown below

-.8680573292E-01
0.1152196690E+01
0.2468541257E+01
0.9869345231E+00
-.3400007235E+00
0.1368798619E+01
-.1919632517E+00
0.1738000531E+00
-.6852306426E+00
0.1830562921E+01
0.1851838872E+01
0.4608874060E+00

I made the code as below.

import os, sys
import re
import math
import numpy as np

to_float = lambda x: float(x)

read = open('./ti_en.dat', 'r')
#print(read)                                                                                                          
read = ''.join(list(read))
read = list(map(to_float, read))

Usually, I used with open and for statements to write code for reading files, but I wanted to write code differently, so I used open and map functions.

However, the following error occurred

 File "_tmp_getdvdl.py", line 10, in <lambda>
    to_float = lambda x: float(x)
ValueError: could not convert string to float: '-'

I made the code the usual way, but it worked well without any errors.

with open('ti_en.dat','r') as fi:
    for i in fi:
        en = float(i)
        print(en)

Why doesn't the first code get an error and the code below get an error when using the same float() function? Thank you.

python

2022-09-20 17:32

1 Answers

''.join("a", "b", "c") becomes "abc". Why do you join?


2022-09-20 17:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.