我在将矢量输入乘以常数时遇到了一些麻烦。基本上我想要一个列表,并将该列表中的每个条目乘以常量。
例如:4 * [1,2,3]将是[4,8,12]。
我尝试以最直接的方式做到这一点我只知道如何编写常量*我想要乘以的列表。但是,这产生了整个不能乘以'float'类型的非int序列。我查看了有关该问题的几个问题(TypeError: can't multiply sequence by non-int of type 'float' 3.3和can't multiply sequence by non-int of type 'float'),我找到的唯一适用的解决方案就是使用float()
。但是,当我尝试这样做时,我又得到了另一个
错误: float()参数必须是字符串或数字,而不是'tuple'
。我不知道该怎么做,我确信有一种简单的方法可以做到这一点,但我不确定它是什么。
if n == m:
if n == 1:
denom = float(r1) * const
ans = identity / denom
return(ans)
这是返回该错误的代码,这是返回第一个错误的代码。
if n == 1:
denom = r1 * const
ans = identity / denom
return(ans)
const是函数中较早定义的变量,r1也早先定义为:
r1 = (1,1,1) #the starting position of the 3 particles: r1, r2, and r3
(评论是因为我继续定义r2和r3。)
这不是家庭作业,所以在提供代码方面没有任何道德义务。
提前致谢。
答案 0 :(得分:0)
有很多方法可以做到这一点。例如,列表理解:
>>> l = [1, 2, 3]
>>> [(4.3 * x) for x in l]
[4.3, 8.6, 12.899999999999999]
答案 1 :(得分:0)
试试这个......
>>> z = [l * 4 for l in [1, 2, 3]];
>>> z
[4, 8, 12]