Demand:
The preceding article is about using the same number of variables as the number of elements in the iterator data variable, but more of the time you do not want to define the corresponding number of variables based on the number of elements (n), but rather with fewer variables (
Def Drop_first_last (Grades):
def avg (my_list): Return
sum (my_list)/len (my_list) I
, *middle, last = Sorted (Grades) return
AVG (middle)
Of course, "star expression" can be in any location, the corresponding unpack elements after the deposit, will form a list (even if there is no corresponding element, but also an empty list). Here you can imagine another example, you are looking at your own nearly 1 years of wages in the water, you want to calculate the first 11 months of the average wage and the month's salary comparison, naturally can do so:
Salary_record = (9000, 9000, 12000, 9000, 7000, 8000, 9000, 9000, 10000,
10000, 8500, 10500)
*trailing_months, cur Rent_month = Salary_record
trailing_avg = SUM (trailing_months)/len (trailing_months) Result
= Current_month > Trailing_avg
Extended:
The example above might be a bit superfluous for the reader, after all, whether it's a tuple or a list, with more other ways to get the results, like the first one to get it straight:
Middle_avg = SUM (sorted (grades) [1:len (Grades)-1])/(Len (Grades)-2)
Of course, there are many ways, it depends on how you feel to achieve a better way to express their ideas. In addition, the star expression has his own unique advantage in dealing with a list of multiple lengths of inequality:
Records = [
(' Jason ', ' SE ', 6],
(' Lee ', ' Python '),
(' Jason ', ' Web ', 2),
]
def show_jason (x, y):
print (' Jason ', X, y)
def Show_lee (s):
print (' Lee ', s)
for tag, *args in records:
if tag = = ' Jason ': C10/>show_jason (*args)
elif tag = = ' Lee ':
Show_lee (*args) in
[a]: Runfile ('/home/jason/codes/ test.py ', wdir= '/home/jason/codes ')
Jason SE 6
Lee Python
Jason Web 2
Here you can also cite an interesting recursive method for finding the elements of a list:
def sum (items): Head
, *tail = items return head
+ sum (tail) if tail else head
sum (range)
out[71]: 45
Of course, we all know that recursion is never a good way to solve a problem, so look at it.