Python-将2D列表中的元素相乘 [英] Python - Multiplying an element from 2D list
问题描述
我想将2D列表中的元素之一乘以整数.但是,执行代码后,我得到以下信息:我期望结果只是一个元组,而不是列表,并且希望它是一个元组而不是列表.
I would like to multiply one of the elements from the 2D list by an integer. However, once I execute the code I get the following: I was expecting the outcome to be just a tuple, rather than a list, and would like for it to be a tuple rather than a list.
[3, 3, 3]
[6, 6, 3, 3, 3, 3]
这是我的代码:
list = [[0.5],[0.3],[0.1]]
def funcOne(juv):
newAd = juv * list[0]
return newAd
def funcTwo(ad,sen):
newSen = (ad* list[1]) + (sen* list[2])
return newSen
print(funcOne(3))
print(funcTwo(2,4))
我对funcOne的期望输出将是3 * 0.5 = 1.5 ,其中"0.5"是列表[0].我不确定如何编辑代码以实现此结果.
My desired output for funcOne would be to have 3*0.5 = 1.5, where "0.5" is list[0]. I am unsure about how to edit my code in order to achieve this outcome.
推荐答案
实际上,我仍然对您对预期输出的解释感到困惑.我只是运行您的代码,输出如下:
Actually I'm still confused about your explanation for the expected output. I just run your code the output is below:
[0.5, 0.5, 0.5]
[0.3, 0.3, 0.1, 0.1, 0.1, 0.1]
您的函数将返回列表而不是将2d矩阵中的元素相乘的原因是因为您以错误的方式对2d矩阵中的元素使用了索引. 这是您的代码:
The reason that your function will return a list instead of multiplying one of the elements in the 2d matrix is that you use the index for the element in the 2d matrix in a wrong way. Here is your code:
list = [[0.5],[0.3],[0.1]]
def funcOne(juv):
newAd = juv * list[0]
return newAd
def funcTwo(ad,sen):
newSen = (ad* list[1]) + (sen* list[2])
return newSen
print(funcOne(3))
print(funcTwo(2,4))
在您的代码中,当您在函数funcOne
中使用juv * list[0]
时,它实际上以3 * [0.5]
执行,其中[0.5]
是2d矩阵(列表)的第一个元素.您可以在Python解释器中运行,然后发现3 * [0.5]
的结果为[0.5, 0.5, 0.5]
,这意味着它仅将列表中的元素复制了3次.
In your code, when you use juv * list[0]
in the function funcOne
, it actually execute as 3 * [0.5]
, where [0.5]
is the first element of the 2d matrix(list). You can run in the Python interpreter and find that the result of 3 * [0.5]
is [0.5, 0.5, 0.5]
, which means it just replicate the elements in the list three times.
如果要像[[0.5 * 3], [0.3], [0.1]]
那样进行计算,则应按如下所示更改代码:
If you want to calculate like [[0.5 * 3], [0.3], [0.1]]
, you should change a little bit of your code as following:
def funcOne(juv):
newAd = juv * list[0][0]
return newAd
def funcTwo(ad,sen):
newSen = (ad* list[1][0]) + (sen* list[2][0])
return newSen
----------更新
----------update
如果要返回像[[1.5], [0.3], [0.1]]
这样的列表.将代码更改为
If you want to return the list like [[1.5], [0.3], [0.1]]
. Change the code to
def funcOne(juv):
list[0][0] = juv * list[0][0]
return list
希望有帮助.
这篇关于Python-将2D列表中的元素相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!