Python - Multiplying an element from 2D list

2019-07-30 00:19发布

问题:

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)