ytk
ytk

Reputation: 2827

How to convert list to float in Python

I'm trying to write a program to look for lines of the form

New Revision: 39772

extract all the numbers, and then find the average. Here is my code:

import re
import statistics

file_name = raw_input("Enter file: ")
file = open(file_name)
revision_nums = []

for line in file:
    line = line.rstrip()
    x = re.findall("New Revision: (\d+)", line)
    if len(x) > 0:
        revision_nums.append(x)

print statistics.mean(revision_nums)

However, I realized that all the elements in revision_nums are stored as lists, and I'm getting this error when I try to run it:

TypeError: can't convert type 'list' to numerator/denominator

I tried:

for i in revision_nums:
    for j in i:
        j = float(j)

and it returns the same error. What am I doing wrong and how can I fix this?

Upvotes: 2

Views: 1311

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

If your lines always start with New Revision: you don't need a regex, you can use str.startswith and str.rsplit:

file_name = raw_input("Enter file: ")
with open(file_name) as f:
    revision_nums = []
    for line in f:
        if line.startswith("New Revision:"):
            revision_nums.append(float(line.rsplit(None,1)[1]))

Which can become a list comp:

with open(file_name) as f:
      revision_nums = [float(line.rsplit(None,1)[1])for line in f 
                      if line.startswith("New Revision:")]

Using with will automatically close your file.

If you have to use re and might have many matches in a line use search and extend, mapping to float:

with open(file_name) as f:
    revision_nums = []
    r = re.compile("New Revision:\s+(\d+)")
    for line in f:
         revision_nums.extend(map(float,r.findall(line)))

Upvotes: 1

f43d65
f43d65

Reputation: 2302

x is the list, even if re.findall found only one match. Try revision_nums.append(x[0])

Upvotes: 3

Related Questions