Home > Blockchain >  how I create a new whole list by dividing a list of tuples in python
how I create a new whole list by dividing a list of tuples in python

Time:03-26

i have a list like this:

[[(62, 57),
  (59, 23),
  (49, 5),
  (138, 10),
  (37, 52),
  (145, 3),
  (13, -1),
  (30, 5),
  (15, 4)],
 [(31, 1),
  (74, 0),
  (85, 8),
  (85, 25),
  (45, 4),
  (38, 0),
  (37, 0),
  (16, 0),
  (102, -1)]]

And I need to create another list from the division by the numbers between parentesis and i have no clue how to do it. I need something like this: [1.08, 2.56, 9.8, and so on] ps. if one of the numbers is 0 filter it.

CodePudding user response:

Use a list comprehension:

my_list = [[(62, 57), (59, 23), (49, 5), (138, 10), (37, 52), (145, 3), (13, -1), (30, 5), (15, 4)],
           [(31, 1), (74, 0), (85, 8), (85, 25), (45, 4), (38, 0), (37, 0), (16, 0), (102, -1)]]

[[a/b for a,b in l if b] for l in my_list]

Output:

[[1.087719298245614, 2.5652173913043477, 9.8, 13.8, 0.7115384615384616, 48.333333333333336, -13.0, 6.0, 3.75],
 [31.0, 10.625, 3.4, 11.25, -102.0]]

NB. if you want to ensure that both numbers are non zero, use if a and b

  • Related