a method of substituting values for similar variables

Asked 2 months ago, Updated 2 months ago, 1 views

I'd like to define 6 lines of a1, a2, a3, b1, b2, b3 shorter for the following code. Is there a good way to use .format(), but it didn't work.

a2 = 2
a3 = 3
b1 = a1**2
b2 = a2**2
b3 = a3**2


2022-09-30 11:22

3 Answers

a* variables have their own values, and b* variables have a common formula. If you want to give it to me, it's like this

>>a1,a2,a3 = 1,2,3
>>>b1,b2,b3 = [n**2 for n in (a1, a2, a3)]

If you want to use a set (for example, if there are many items), you can use it like this.

b1, b2, b3 = [n**2 for n in vals ]

2022-09-30 11:22

I think it would be good to make it a list.

b = [i**2 for i in a ]

2022-09-30 11:22

For Python 3.8 and later, use walrus operator as follows:


*I don't recommend it

2022-09-30 11:22

If you have any answers or tips

© 2022 OneMinuteCode. All rights reserved.