简体   繁体   English

将字符串列表转换为浮点列表并获取所有值的总和

[英]Converting a list of strings to a list of floats and getting the sum of all values

I have the following list in python 3. 我在python 3中有以下列表。

['12 32.12 453\n', '54 123 65\n', '12 32\n', '12 32 54 765 876\n']

How do I remove the \\n from the end of each entry? 如何从每个条目的末尾删除\\ n? And how do I convert the list to 以及如何将列表转换为

[12.0, 32.12, 453.0, 54.0, 123.0, 65.0, 12.0, 32.0, 12.0, 32.0, 54.0, 765.0, 876.0]

?

I need a way to convert each number to a float and add them all together to get a sum. 我需要一种将每个数字转换为浮点数并将它们加在一起以求和的方法。 this This is my code so far: 到目前为止,这是我的代码:

def calc_sum(filename):
    new_list = []
    try:
        file = open(filename)
    except:
        print("oops")
        return None
    line = file.readlines()
    print(line)

Convert to a list of floats: 转换为浮点数列表:

>>> a = ['12 32.12 453\n', '54 123 65\n', '12 32\n', '12 32 54 765 876\n']    
>>> k = [float(y) for lst in (x.split() for x in a) for y in lst]
>>> k
[12.0, 32.12, 453.0, 54.0, 123.0, 65.0, 12.0, 32.0, 12.0, 32.0, 54.0, 765.0, 876.0]

Get the sum: 得到总和:

>>> sum(k)
2522.12

All in one line: 一站式:

>>> sum(float(y) for lst in (x.split() for x in a) for y in lst)
2522.12

Explanation : 说明

To see what's going on, here's equivalent code without the use of list/generator comprehensions: 要查看发生了什么,这里是等效代码,没有使用列表/生成器理解:

k = []
for x in a:
    x = x.split()
    k.append(x)

k is now [['12', '32.12', '453'], ['54', '123', '65'], ['12', '32'], ['12', '32', '54', '765', '876']] . k现在为[['12', '32.12', '453'], ['54', '123', '65'], ['12', '32'], ['12', '32', '54', '765', '876']] We've got rid of the newline characters and have a list of lists, each inner list containing strings (which can be converted to floating point numbers). 我们摆脱了换行符,并有了一个列表列表,每个内部列表都包含字符串(可以将其转换为浮点数)。 Next, we flatten the list: 接下来,我们整理列表:

m = []
for sublist in k:
    for x in sublist:
        m.append(x)     

m is ['12', '32.12', '453', '54', '123', '65', '12', '32', '12', '32', '54', '765', '876'] . m['12', '32.12', '453', '54', '123', '65', '12', '32', '12', '32', '54', '765', '876'] Finally, we convert all string values to floats: 最后,我们将所有字符串值转换为浮点数:

k = []
for x in m:
    k.append(float(x))

k is [12.0, 32.12, 453.0, 54.0, 123.0, 65.0, 12.0, 32.0, 12.0, 32.0, 54.0, 765.0, 876.0] and sum(k) will yield the sum over all the elements. k[12.0, 32.12, 453.0, 54.0, 123.0, 65.0, 12.0, 32.0, 12.0, 32.0, 54.0, 765.0, 876.0]并且sum(k)将得出所有元素的总和。

Try using a map : 尝试使用map

>>> x = ['12 32.12 453\n', '54 123 65\n', '12 32\n', '12 32 54 765 876\n']
>>> map(float, ''.join(x).split())
[12.0, 32.12, 453.0, 54.0, 123.0, 65.0, 12.0, 32.0, 12.0, 32.0, 54.0, 765.0, 876.0]
>>> 

The strip method will remove trailing characters and the split method will split each line at spaces. strip方法将删除结尾字符, split方法将在空格处分隔每一行。 Then use float to convert each chunk from string to float and sum to get a sum. 然后使用float将每个块从字符串转换为float和sum以获得总和。 Iterate over lines, sum line partials and you are done. 遍历行,对行的部分求和,就完成了。

def calc_sum(filename)
    result = 0.0

    with open(filename) as stream:
        for line in stream:
            values = line.strip("\n").split(" ")
            result += sum(float(x) for x in values)

    return result

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

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