简体   繁体   English

如何在Python中将列表转换为浮动

[英]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: 但是,我意识到Revification_nums中的所有元素都存储为列表,并且在尝试运行它时遇到此错误:

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? 我在做什么错,我该如何解决?

x is the list , even if re.findall found only one match. xlist ,即使re.findall仅找到一个匹配项。 Try revision_nums.append(x[0]) 尝试revision_nums.append(x[0])

If your lines always start with New Revision: you don't need a regex, you can use str.startswith and str.rsplit: 如果您的行始终以New Revision:开始New Revision:您不需要正则表达式,则可以使用str.startswith和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. with使用将自动关闭文件。

If you have to use re and might have many matches in a line use search and extend , mapping to float: 如果必须使用re并且一行中可能有许多匹配项,请使用search和extend ,将其映射为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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM