列表中每个元素相乘python_Python-将2D列表中的元素相乘

1586010002-jmsa.png

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]

This is my 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))

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]

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))

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.

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

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

Hope it helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值