I have a list contains around 200 numbers. I need a list fraction of them. I mean I have a=[111,23,25,12,61]
I want b=[1/111,1/23,1/25,1/12,1/61]
How can i do that?
CodePudding user response:
With a list comprehension:
[1.0/x for x in a]
CodePudding user response:
You can use map
to apply a function to every element of a list:
n = [111, 23, 25, 12, 61]
n_fractions = map(lambda x: 1/x, n)
# [0.009009009009009009, 0.043478260869565216, 0.04, 0.08333333333333333, 0.01639344262295082]
You can also use the built-in fractions.Fraction
class to properly express the values as fractions:
n_fractions = list(map(lambda x: Fraction(1, x), n))
# [Fraction(1, 111), Fraction(1, 23), Fraction(1, 25), Fraction(1, 12), Fraction(1, 61)]