Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- __author__ = 'Work'
- '''
- You need to unpack N-elements from an iterable, but the iterable may be longer than N elements, causing a
- "too many values to unpack" exception.
- '''
- # Python "star expressions" is an option to address this problem.
- '''
- Ex: You run a course and decide at the end of the semester that you're going to drop the first and last hw grades,
- and only average the rest of them. If there are only 4 assignments, maybe you simply unpack all 4, but what if there
- where 24? A star expression makes this easy:
- '''
- import statistics
- def drop_first_last(grades):
- first, *middle, last = grades
- return statistics.mean(middle)
- def drop_lowest_double_highest(grades):
- grades.sort()
- first, *middle, last = grades
- middle.append(2 * last)
- return statistics.mean(middle)
- #x = drop_first_last([3,3,3,1])
- # x = drop_lowest_double_highest([3,4,6,2,3,1,8,3,2,5,6])
- #
- # y = [3,4,6,2,3,1,8,3,2,5,6]
- # print('Length of list y: ',len(y))
- # y.sort()
- # print('Sorted list y: ',y)
- # y.remove(1) # Drop lowest
- # print('List y lowest popped: ', y)
- #
- # print('Mean: ', sum(y)/len(y))
- #
- # y[-1] *= 2
- # print('Average with last grade doubled: ', sum(y)/len(y))
- # print('X: ', x)
- '''
- Use Case #2:
- Suppose you have user records that consist of a name and email address, followed by an arbitrary number of phone numbers.
- You could unpack the records like this:
- '''
- name, email, *phone_numbers = record
- print(name)
- print(phone_numbers)
- # Worth noting that phone_numbers variable will always be a list no matter how many variables are unpacked.
- '''
- Starred variable can also be the first one in the list.
- Ex: You have a sequence of values representing your company's sales figures for the last eight quarters.
- If you want to see how the most recent quarter stacks up to the average of the first seven, try this:
- '''
- # Psuedocode
- # *trailing_qtrs, current_qtr, = sales_record
- # trailing_avg = sum(trailing_qtrs)/ len(trailing_qtrs)
- # return avg_comparison(trailing_avg, current_qtr)
- *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
- print(trailing)
- print(current)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement