Search code examples
pythonarraysmultiplication

array multiplication with integer


I have a 2D array "pop" in python. I want to multiply each element of column one with an integer. I used the following code

temp[i] = b*pop[i,0]+a*pop[i,1] 

But it is returning error "list indices must be integers or slices, not tuple"


Solution

  • import random
    from random import sample
    rows=20
    a,b = 0.5,1 
    pop=list(zip(sample(range(1, 100000), rows),sample(range(1, 100000), rows)))
    profit = sample(range(1, 100000), rows)
    #print(pop,profit)
    mycombined=list(zip(pop,profit))
    combined_array = np.asarray(mycombined)
    
    print(combined_array)
    
    m = len (combined_array) 
    it = 1500 
    #alpha = 0.01 
    
    J=0
    for i in range(1,m,1): 
         bpop=combined_array[i][0][0]
         apop=combined_array[i][0][1]
         aprofit=combined_array[i][1]
         temp=(bpop+apop-aprofit)**2
         J=J+temp
    

    Now you have a list of lists and can use list comprehensions to change the values

    1. pop contains a two variable tuple
    2. profit is a list of random numbers
    3. the result is a list of lists or tuples