Python - Multiplying an element from 2D list

会有一股神秘感。 提交于 2020-01-05 05:40:13

问题


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.


回答1:


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.




回答2:


Just return the list converted to tuple:

def funcOne(juv):    
    newAd = juv * list[0]
    return tuple(newAd) # convert to tuple

Same goes for funcTwo.


Then, to reproduce your desired output use:

>>> list = [[3], [6], [3]]
>>> print(funcOne(3))
(3, 3, 3)
>>> print(funcTwo(2, 4))
(6, 6, 3, 3, 3, 3)


来源:https://stackoverflow.com/questions/40250819/python-multiplying-an-element-from-2d-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!