Smooth python and cookbook learning notes (2), pythoncookbook

Source: Internet
Author: User

Smooth python and cookbook learning notes (2), pythoncookbook
1. Value assignment of the packet splitting and decompression sequence of tuples

Any sequence (or iteratable object) can be decompressed and assigned to multiple variables through a simple assignment statement. The only premise is that the number of variables must be the same as the number of sequential elements.

1. Parallel assignment:

>>> X = (1, 2) >>> a, B = x # tuples >>> a1 >>> b2

2. Use the * operator to split an iteratable object as a function parameter:

>>> Divmod (20, 8) #20 calculate the remainder of 8, 2*8 + 4 = 20 (2, 4) >>> t = (20, 8) >>> divmod (* t) (2, 4) >>> quotient, remainder = divmod (* t) >>>> quotient, remainder # quotient and remainder (2, 4)

3. Use * args in the function to obtain uncertain number of parameters:

>>> a, b, *rest = range(5)>>> a, b, rest (0, 1, [2, 3, 4]) >>> a, b, *rest = range(3)>>> a, b, rest(0, 1, [2]) >>> a, b, *rest = range(2) >>> a, b, rest(0, 1, [])

4. In parallel assignment, * the prefix can only be used before a variable name, but this variable can appear in any position of the assignment expression:

>>> a, *body, c, d = range(5) >>> a, body, c, d (0, [1, 2], 3, 4) >>> *head, b, c, d = range(5) >>> head, b, c, d ([0, 1], 2, 3, 4)

.

 

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.