Hi, this is Milo, a blogger who would like to share his test development techniques, interview tips and growing experiences with you!
Welcome everyone to pay attention to my public number: test development pit goods.
Let’s have a fun day and do a little trick of ignoring (discarding) variables.
Everybody knows that
Most people know about multivariable assignment, such as:
a, b = 1.2
Copy the code
You should also know that swapping variables can be done without generating temporary variables:
a, b = b, a
Copy the code
Abandoned variable
So today I’m going to show you a different one. As we know, variables start with a letter and can be followed by a letter/number/underscore. What happens if the variables are named separately with an underscore?
As you can see, no error is reported, which means the operation is accepted. Variables named _ are automatically discarded as obsolete variables.
Usage scenarios
For example, if I want to execute a method N times, but I don’t care how many times I execute it, I can write:
def func() :
print("yyds")
n = 10
for _ in range(n):
func()
Copy the code
Since we don’t need this I, we can set it to _.
Let’s think about whether we can also use this when we assign to arrays. Let’s say I have an array that looks like this:
a = ["Top dog"."190cm"."3 sets of siheyuan"."Love to play ball"."Very handsome."."Married"]
Copy the code
You can see that the order of the array is: name, height, real estate, hobbies, appearance, and marital status. As a girl, I care more about his height, real estate, appearance and marital status.
For comparison, I have a number of similar blind dates that I will consider. So I’m going to list all of these conditions.
Let’s look at the original way:
height = a[1]
house = a[2]
feature = a[4]
married = a[5]
Copy the code
But if you use _ to discard some variables, you can write:
_, height, house, _, feature, married = a
Copy the code
So you can get rid of the variables that you don’t want, which isn’t very useful to be honest. But it’s a trick. Did you Get it?