-2

I was reading from a file and was able to compute a list, but sadly it reads as : ['40\n', '35\n', '49\n', '53\n', '38\n', '39\n', '40\n', '37\n', '49\n', '34\n', '38\n', '43\n', '47\n', '\n'] when I would like it to read as: ['40', '35', '49', '53', '38', '39', '40', '37', '49', '34', '38', '43', '47'] I know I have to append it and/or slice it in order to turn in into floats. I am really stuck on this part. This is the one part that will make the rest of my code work. Any help is appreciated!

Tupteq
  • 2,986
  • 1
  • 21
  • 30
  • Can you share the code you used to read from the file? – AMC Feb 15 '20 at 00:37
  • Show us your code and data. – Tupteq Feb 15 '20 at 00:37
  • 1
    Does this answer your question? [How to read a file without newlines?](https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines) – AMC Feb 15 '20 at 00:37
  • Also: https://stackoverflow.com/questions/4319236/remove-the-newline-character-in-a-list-read-from-a-file, https://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline – AMC Feb 15 '20 at 00:37

2 Answers2

1

'\n' is a linebreak. It can be ignored when there is a number before it. Thus you could do:

a = ['40\n', '35\n', '49\n', '53\n', '38\n', '39\n', '40\n', '37\n', '49\n', '34\n', '38\n', '43\n', '47\n', '\n']

[int(i) for i in a if i!='\n']
[40, 35, 49, 53, 38, 39, 40, 37, 49, 34, 38, 43, 47]

if you want floats, just do:

[float(i) for i in a if i!='\n']
[40.0, 35.0, 49.0, 53.0, 38.0, 39.0, 40.0, 37.0, 49.0, 34.0, 38.0,

43.0, 47.0]

Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • If my file is called "content" would it be [float(content) for content in a if (content)!='\n'] – NewHere Feb 15 '20 at 01:24
  • @NewHere NO. you cannot do that. `i` is not a file but rather an index. You should first read the file into python and iterate over the lines – Onyambu Feb 16 '20 at 15:34
0
a = ['40\n', '35\n', '49\n', '53\n', '38\n', '39\n', '40\n', '37\n', '49\n', '34\n', '38\n', '43\n', '47\n', '\n']

float_a = [float(x[:-1]) for x in a if x != '\n']

You can easily convert this list with a list comprehension to a list of floats.

Pingmader
  • 61
  • 5