矩阵问题 Python [英] Matrix problem Python

查看:26
本文介绍了矩阵问题 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有矩阵:

x=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U2']]

我怎样才能从 x 中获取所有数据,除了最后一个.然后我需要对这些元素求和.

How can I take all data from x, except the last one. Then I need to sum this elements.

这就是我需要的:sum=1+7+1.5+8+2+5.5= ??

谢谢

我尝试:

> x=[['1', '7', 'U1'], ['1.5', '8',
> 'U1'], ['2', '5.5', 'U2']]
> 
> sum(sum(el[:-1]) for el in x)

但收到错误:

回溯(最近一次调用最后一次):
文件xxx.py",第 3 行,在sum(sum(el[:-1]) for el in x) File "xxx.py", line 3, insum(sum(el[:-1]) for el in x) TypeError: 不支持的操作数类型对于 +: 'int' 和 'str'

Traceback (most recent call last):
File "xxx.py", line 3, in sum(sum(el[:-1]) for el in x) File "xxx.py", line 3, in sum(sum(el[:-1]) for el in x) TypeError: unsupported operand type(s) for +: 'int' and 'str'

推荐答案

您可以使用 [:-1] 将除最后一个索引之外的所有元素分开.

You can take all elements apart from the last one indexing with [:-1].

要取那个总和,请尝试 sum(sum(float(el) for el in els[:-1]) for els in x).

To take that sum, try sum(sum(float(el) for el in els[:-1]) for els in x).

如果列表中确实有字符串,则可能需要强制转换元素.另外,如果总是有 3 个元素,这可能会快一点:

If you actually have strings in the list, you might need to cast the elements. Also, if there are always 3 elements, this could be a bit faster:

sum(float(a) + float(b) for a,b,_ in x) 

这篇关于矩阵问题 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆