Python Technique Detailed Explanation of Sequence Splitting

  • 2021-12-05 06:45:01
  • OfStack

Catalog tuple splitting string splitting discarding values when splitting nested sequence splitting splitting from iterative objects of arbitrary length summary of references

Tuple splitting

Tuple splitting is one of the most common splits, as shown below:


p = (4, 5)
x, y = p 
print(x, y) # 4 5

If it is written as


x, y, z = p

Then an ValueError exception is thrown: "not enough values to unpack (expected 3, got 2)"
If it is written as


p = (4, 5, 6)
x, y = p

Then an ValueError exception is thrown: "too many values to unpack (expected 2)"

String splitting

The splitting of the string is illustrated as follows:


s = 'Hello'
a, b, c, d, e = s
print(a) # H

Discard values when splitting

If you want to discard certain values when splitting, you can use a variable name that is not used as the name of the discarded value (often choose '_' as the variable name), as follows:


s = 'Hello'
a, b, _, d, _ = s
print(a) # H

Nested sequence splitting

Python also provides a concise syntax for splitting nested sequences. As shown below, we split a more complex heterogeneous list:


data = ['zhy', 50, 123.0, (2000, 12, 21)]
name, shares, price, (year, month, day) = data
print(year) # 2000

If you want to get the tuple (2000, 12, 21) that represents the timestamp in its entirety, you have to write this:


data = ['zhy', 50, 123.0, (2000, 12, 21)]
name, shares, price, date = data
print(date) # (2000, 12, 21)

Split from an iterative object of arbitrary length

As we said earlier, if we want to decompose\ (N\) elements from an iterable object, but if the iterable object is longer than\ (N\), the exception "too many values to unpack" will be thrown. The solution to this problem is to use the "*" expression.

For example, if we give a student's score, we want to remove one highest score and one lowest score, and then average the remaining students, we can write this:


def avg(data: list):
    return sum(data)/len(data)
#  Remove the highest score and the lowest score and make an average score statistics 
def drop_first_last(grades):
    first, *middle, last = grades
    return avg(middle)
print(drop_first_last([1,2,3,4])) # 2.5

In another case, if there are 1 user record, which consists of name + email + any number of telephone numbers, we can break down the user record as follows:


record = ['zhy', 'zhy1056692290@qq.com', '773-556234', '774-223333']
name, email, *phone_numbers = record
print(phone_numbers) # ['773-556234', '774-223333']

In fact, it is also legal if the phone number is empty, in which case phone_numbers is an empty list.


record = ['zhy', 'zhy1056692290@qq.com']
name, email, *phone_numbers = record
print(phone_numbers) # []

There is also a more ingenious use. If we need to traverse a list of variable-length tuples, the length of these tuples is not 1. Then the * expression can greatly simplify our code at this time.


x, y, z = p
0

* expressions are also particularly useful when splitting some complex strings.


x, y, z = p
1

* Expressions can also be used in conjunction with nested splitting and variable discarding as we mentioned earlier.


x, y, z = p
2

Finally, I will introduce a kind of black magic that * expression is used for recursive function. For example, when combined with recursive sum, it can be written as follows:


items = [1, 10, 7, 4, 5, 9]
def sum(items):
    head, *tail = items
    return head + sum(tail) if tail else head
print(sum(items)) # 36

However, Python is not good at recursion due to the limitation of its own recursion stack. Our last example of recursion can be used as an academic attempt, but it is not recommended to use it in practice.

References

[1] Martelli A, Ravenscroft A, Ascher D. Python cookbook [M]. "O 'Reilly Media, Inc.", 2005. Mathematics is the art of symbols, and music is the language of the upper bound.

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: