Home > other >  How to divide or multiply between elements of a tuple in python?
How to divide or multiply between elements of a tuple in python?

Time:11-04

I have the next tuple as result of a sql query:

tuple1 = [(245, 57)]
tuple2 = [(11249, 5728)]
tuple3 = [(435, 99)]

and I need to divide the 57 between 245 and the same with the rest.

I can access individual elements with:

[x[0] for x in rows]

but when I do:

a = [x[1] for x in rows] / [x[0] for x in rows]

I get TypeError: unsupported operand type(s) for /: 'list' and 'list'

CodePudding user response:

a = [x[1] for x in rows] / [x[0] for x in rows]

will attempt to divide a list by a list.

What you meant to do is:

a = [x[1] / x[0] for x in rows]

which is divide elements per item in list.

CodePudding user response:

Using multiple names can increase readability:

a = [y / x for x, y in rows]

CodePudding user response:

Another option would be

list(map(lambda x: x[1]/x[0] if x[0] else 0,rows))
  • Related