我在python 3中有以下列表。
['12 32.12 453\n', '54 123 65\n', '12 32\n', '12 32 54 765 876\n']
如何从每个条目的末尾删除\ n?我如何将列表转换为
[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]
我需要一种方法将每个数字转换为浮点数并将它们全部加在一起以获得总和。这是我到目前为止的代码:
def calc_sum(filename):
new_list = []
try:
file = open(filename)
except:
print("oops")
return None
line = file.readlines()
print(line)
答案 0 :(得分:1)
转换为浮动列表:
>>> 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]
得到总和:
>>> sum(k)
2522.12
全部在一行:
>>> sum(float(y) for lst in (x.split() for x in a) for y in lst)
2522.12
<强>解释强>:
要查看正在进行的操作,请使用以下等效代码,而不使用list / generator comprehensions:
k = []
for x in a:
x = x.split()
k.append(x)
k
现在是[['12', '32.12', '453'], ['54', '123', '65'], ['12', '32'], ['12', '32', '54', '765', '876']]
。我们已经删除了换行符并且有一个列表列表,每个列表包含字符串(可以转换为浮点数)。接下来,我们将列表展平:
m = []
for sublist in k:
for x in sublist:
m.append(x)
m
是['12', '32.12', '453', '54', '123', '65', '12', '32', '12', '32', '54', '765', '876']
。最后,我们将所有字符串值转换为浮点数:
k = []
for x in m:
k.append(float(x))
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)
将产生所有元素的总和。
答案 1 :(得分:0)
尝试使用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]
>>>
答案 2 :(得分:-1)
strip
方法将删除尾随字符,split
方法将在空格处分割每一行。然后使用float
将每个块从字符串转换为float和sum
以获得总和。迭代线,求和线部分,你就完成了。
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