[英]Python error: TypeError: float() argument must be a string or a real number, not 'list'
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.我有一个 sample.txt,其中包含一堆文本,整个文本都带有数字。 My goal is to parse the lines for the numbers only and then find the sum.
我的目标是仅解析数字的行,然后找到总和。
Here is the sample.txt:这是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))
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您可以使用 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/我认为更好的方法是使用 map function https://www.geeksforgeeks.org/python-map一次转换整个列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.