Home > database >  how to save elements as a variable in python?
how to save elements as a variable in python?

Time:12-11

I have an array

a=[1,3,7,5,8,9,2,1]

and this matrix


       1st,2nd,3rd
matrix=[[1,3,10],
        [3,7,20],
        [5,8,12],
        [2,3,30],
        [3,3,14],
        [8,9,25],
        [5,3,30],
        [7,5,11],
        [8,9,21],
        [2,1,0],
        [9,2,15]]

I want to "save" or "store" the elements from array a in pairs as variable such as this form

(1st,2nd),(2nd,3rd),(3rd,4th), and so on till (7th,8th)

looking like this:

(1,3),(3,7),(7,5),(5,8),(8,9),(9,2),(2,1)

Trying to save these "pairs" as above format to identify the 3rd column from matrix using 1st and 2nd column info as pair:

       1st,2nd,3rd
matrix=[[1,3,**10**],
        [3,7,**20**],
        [5,8,**12**],
        [2,3,30],
        [3,3,14],
        [8,9,25],
        [5,3,30],
        [7,5,**11**],
        [8,9,**21**],
        [2,1,**0**],
        [9,2,**15**]]

To summarize, Not necessarily need to save the "pairs". I just want the 3rd column information driven from 1st and 2nd column from the matrix by pairs from the array a

lastly, I want to calculate the sum of the determined 3rd column elements from pairs info:

(1,3),(3,7),(7,5),(5,8),(8,9),(9,2),(2,1)

10 20 11 12 21 15 0=sum1

Any help?

CodePudding user response:

You can use dictionary comprehension and tuple comprehension for this task:

matrix=[[1,3,10],
        [3,7,20],
        [5,8,12],
        [2,3,30],
        [3,3,14],
        [8,9,25],
        [5,3,30],
        [7,5,11],
        [8,9,21],
        [2,1,0],
        [9,2,15]]
column_1_and_2 = {i: j[:-1] for i, j in enumerate(matrix)}
column_3 = tuple(i[-1] for i in matrix)
summed_column_3 = sum(column_3)

CodePudding user response:

First let's create a dictionary to store the values corresponding to the pairs:

pair2val = dict()
a=[1,3,7,5,8,9,2,1]
matrix=[[1,3,10],
        [3,7,20],
        [5,8,12],
        [2,3,30],
        [3,3,14],
        [8,9,25],
        [5,3,30],
        [7,5,11],
        [8,9,21],
        [2,1,0],
        [9,2,15]]
for i in range(len(a)-1):
   pair2val[(a[i],a[i 1])] = 0

Now let's look for the values in the matrix and calculate the sum of them:

sum_ = 0
for list_ in matrix:
    cur_pair = (list_[0],list_[1])
    if cur_pair in pair2val:
       pair2val[cur_pair]  = list_[2]
       sum_  = list_[2]
print(f"sum: {sum_}")
print(f"pairs: {pair2val}")

Output:

sum: 114
pairs: {(1, 3): 10, (3, 7): 20, (7, 5): 11, (5, 8): 12, (8, 9): 46, (9, 2): 15, (2, 1): 0}
  • Related