In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about the process of sequence splitting in Python, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Tuple split
Tuple splitting is the most common kind of split. Examples are as follows:
P = (4,5) x, y = p print (x, y) # 4 5
If written as
X, y, z = p
Then a ValueError exception is thrown: "not enough values to unpack (expected 3, got 2)"
If written as
P = (4,5,6) x, y = p
Then a ValueError exception is thrown: "too many values to unpack (expected 2)"
String splitting
The split of the string is as follows:
S = 'Hello'a, b, c, d, e = sprint (a) # H discarded values
If you want to discard certain values when splitting, you can use an unused variable name as the name of the discarded value (often choose'_'as the variable name), as shown below:
S = 'Hello'a, b, _, d, _ = sprint (a) # H nested sequence split
Python also provides concise syntax for splitting nested sequences. We split a more complex heterogeneous list as shown below:
Data = ['zhy', 50, 123.0, (2000, 12, 21)] name, shares, price, (year, month, day) = dataprint (year) # 2000
If you want to get the complete (2000, 12, 21) tuple that represents the timestamp, then you have to write:
Data = ['zhy', 50, 123.0, (2000, 12, 21)] name, shares, price, date = dataprint (date) # (2000, 12, 21) split from an iterable object of any length
As we said before, if we want to decompose\ (N\) elements from an iterable object, but if the iterable object is longer than\ (N\), an 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 and want to get rid of the highest score and the lowest score, and then average the rest of the students, we can write like this:
Def avg (data: list): return sum (data) / len (data) # remove the highest score and the lowest score and then do the average score statistics def drop_first_last (grades): first, * middle, last = grades return avg (middle) print (drop_first_last)
In another case, if there are some user records, which are composed of name + email + any number of phone numbers, we can decompose the user record as follows:
Record = ['zhy',' zhy1056692290@qq.com', '773-556234,' 774-223333'] name, email, * phone_numbers = recordprint (phone_numbers) # ['773-556234,' 774-223333']
In fact, if it is legal that the phone number is empty, the phone_numbers is an empty list.
Record = ['zhy',' zhy1056692290@qq.com'] name, email, * phone_numbers = recordprint (phone_numbers) # []
There is another use that is more ingenious. If we need to traverse a list of variable-length tuples, these tuples vary in length. Then the * expression at this time can greatly simplify our code.
Records = [('foo', 1,2), (' bar', 'hello'), (' foo', 3,4)] for tag, * args in records: if tag = = 'bar': print (args) # [' hello']
* expressions are also particularly useful when splitting complex strings.
Line = "nobody:*:-2:-2:-2:Unprivileged User:/var/empty:/usr/bin/false" uname, * fields, home_dir, sh = line.split (':') print (home_dir) # / var/empty
* expressions can also be used in conjunction with the nested splitting and variable discarding we mentioned earlier.
Record = ['ACME', 50, 123.45, (128,18, 2012)] name, * _, (* _, year) = recordprint (year) # 2012
Finally, we introduce a kind of dark magic that * expressions are used for recursive functions, such as when combined with recursive sums:
Items = [1,10,7,4,5,9] def sum (items): head, * tail = items return head + sum (tail) if tail else headprint (sum (items)) # 36
However, Python is not good at recursion because of its own recursive stack limitations. Our last recursive example can be used as an academic attempt, but it is not recommended to use it in practice.
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 world.
After reading the above, do you have any further understanding of the process of sequence splitting in Python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.