1. 2. Extract elements from iterations of any length

Source: Internet
Author: User
The problem is that you want to extract N elements from iterable, but there may be more than N iterable elements, resulting in an exception of "tomanyvaluestounpack. Solution: the Python expression (starexpression) can be used to solve this problem. For example, if you decide to give up the highest and lowest scores at the end of the semester, just take the remaining average score, as shown in figure

The problem is that you want to extract N elements from iterable, but there may be more than N iterable elements, resulting in an exception of "to define values to unpack. Solution: the Python expression (star expression) can be used to solve this problem. For example, if you decide to give up the highest and lowest scores at the end of the semester, just take the remaining average score, as shown in figure

Problem

If you want to extract N elements from iterable, but there may be more than N iterable elements, the exception of "to define values to unpack" may occur.

Solution

The Python expression (star expression) can be used to solve this problem. For example, if you decide to give up the highest and lowest scores at the end of the semester and only take the remaining average score, if there are only four courses, you can simply pressurize all four, but what if there are 24 courses? Expressions can easily achieve:

def drop_first_last(grades):    first, *middle, last = grades    return avg(middle)

In another example, if you have a user record containing name, email, and phone number, you can pressurize the record as follows:

>>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')>>> name, email, *phone_numbers = user_record>>> name'Dave'>>> email'dave@example.com'>>> phone_numbers['773-555-1212', '847-555-1212']>>>

It is worth noting that the variablephone_numbersWill always be a list, no matter how many phone numbers (including None) are extracted, any usephone_numbersThe Code does not consider whether it is a list or any additional type check.

* Variables can also start at the beginning of the list. For example, if you have a sequence that reflects the company's sales records for the past eight quarters, if you want to see if the records for the last quarter are higher than the average value for the first seven quarters, you can do this:

*trailing_qtrs, current_qtr = sales_recordtrailing_avg = sum(trailing_qtrs) / len(trailing_qtrs)return avg_comparison(trailing_avg, current_qtr)

In the Python interpreter, you can see the following results:

>>> *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]>>> trailing[10, 8, 7, 1, 9, 5, 10]>>> current3

Discussion

Extended iterative unpacking is designed for unpacking of iterative sequences of any position or length. Generally, these iterations have known components or patterns in the structure (for example, the number 1 is followed by a phone number) * expressions allow developers to easily extract these patterns, instead of getting the elements in the iteration sequence as you want.

It is worth noting that * syntax is particularly useful for the sequence of tuples with unknown length. Assume that there is a sequence of tagged tuples:

records = [     ('foo', 1, 2),     ('bar', 'hello'),     ('foo', 3, 4),]def do_foo(x, y):    print('foo', x, y)def do_bar(s):    print('bar', s)for tag, *args in records:    if tag == 'foo':        do_foo(*args)    elif tag == 'bar':        do_bar(*args)

* Decompression is also useful when combined with processing specific strings, for example:

>>> line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'>>> uname, *fields, homedir, sh = line.split(':')>>> uname'nobody'>>> homedir'/var/empty'>>> sh'/usr/bin/false'>>>

Sometimes you may want to extract some values and discard them. You cannot specify only one * during decompression. You can use a common variable name to discard, such_Orign(Ignore ). Example:

>>> record = ('ACME', 50, 123.45, (12, 18, 2012))>>> name, *_, (*_, year) = record>>> name'ACME'>>> year2012>>>

* Decompression and list processing are similar in different functional languages. For example, if you have a list, you can easily break it into headers and tails:

>> items = [1, 10, 7, 4, 5, 9]>>> head, *tail = items>>> head1>>> tail[10, 7, 4, 5, 9]>>>

Someone may want to write such a function and execute such a division to complete a smart recursive algorithm:

>>> def sum(items):...     head, *tail = items...     return head + sum(tail) if tail else head...>>> sum(items)36>>>

However, it should be noted that, due to inherent restrictions, recursion is not really a Python strength. Therefore, the above Code can only be regarded as academic value in implementation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.