Home > Mobile >  Python error: TypeError: float() argument must be a string or a real number, not 'list'
Python error: TypeError: float() argument must be a string or a real number, not 'list'

Time:08-24

Hello I am new to programming and taking online courses at the moment. I am stuck on this specific exercise:

I have a sample.txt that contains a bunch of text with numbers all throughout the text. My goal is to parse the lines for the numbers only and then find the sum.

Here is the sample.txt:

Why should you learn to write programs? 7746
12 1929 8827
Writing programs (or programming) is a very creative 
7 and rewarding activity.  You can write programs for 
many reasons, ranging from making your living to solving
8837 a difficult data analysis problem to having fun to helping 128
someone else solve a problem.  This book assumes that 
everyone needs to know how to program ...

Here is my code:

import re
name = input('Enter File: ')
if len(name) < 1 :
    name = 'sample.txt'
handle = open(name)
numlist = list()
for line in handle :
    line = line.rstrip()
    items = re.findall('[0-9] ', line)
    if len(items) > 0 :
        #print(items)
        num = float(items[0: ])
        numlist.append(num)
print(sum(numlist))

CodePudding user response:

You are trying to convert a list to a float.

num = float(items[0:])
# note, the [0:] is redundant, it will just return the whole list

You can either convert the whole list at once using map

nums = list(map(float, items))

Or you can convert them one at a time like this

nums = []
for item in items:
  nums.append(float(item))

I think the better way is to convert the whole list at once using the map function https://www.geeksforgeeks.org/python-map-function/

  • Related