The form of a Python assignment statement

Source: Internet
Author: User

The form of a Python assignment statement
1. Basic Assignment

>>> a=‘test‘

2. Tuple assignment operation (position)

>>> a,b=‘this‘,‘is‘    #写入了2个元组,只是省略了括号>>> a‘this‘>>> b‘is‘>>> x=‘this‘>>> y=‘is‘>>> a,b=x,y   #省略元组括号,将右侧元组的值赋给右侧元组中的变量>>> a‘this‘>>> b‘is‘>>>>>> [a,b,c]=(‘this‘,‘is‘,‘a‘)      #最后元组和列表赋值已通用,接受右侧是任意类型的序列(也可以是可迭代的对象),如元组、字符串>>> a‘this‘>>> b‘is‘>>> c‘a‘>>> [a,b,c]=‘thi‘      #此处为字符串>>> a‘t‘>>> c‘i‘>>> [a,b,c]=‘this‘   #右侧元素的数目与左侧的变量数量要相同,不然要报错,这样就有了扩展的序列的解包。Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: too many values to unpack (expected 3)

3. List assignment operation (position)

>>> [a,b]=[‘test‘,‘a‘]>>> a‘test‘>>> b‘a‘>>>

4. Sequence assignment operation (general)

>>> a,b,c,d=‘test‘>>> a‘t‘>>> d‘t‘>>>

5. Extended Sequence Unpacking

>>> a,*b=‘test‘            #  *号在末变量>>> a‘t‘>>> b[‘e‘, ‘s‘, ‘t‘]    #为列表>>> *a,b=‘test‘       #   *在首变量,b匹配最后一项,而a匹配最后一项之前的所有项>>> a[‘t‘, ‘e‘, ‘s‘]>>> b‘t‘>>> a,*b,c=‘googbye‘          #      *在中间的变量>>> a‘g‘>>> c‘e‘>>> b[‘o‘, ‘o‘, ‘g‘, ‘b‘, ‘y‘]>>>

6. Multi-objective assignment operation, shared reference

>>> a=b=‘test‘>>> a‘test‘>>> b‘test‘>>>

7. Enhanced assignment operations

>>> s=[1,2]>>> s +=[3]       #此处python不会使用较慢的+合并,而是调用速度快的extend方法合并。此处+并非生成新的对象。+=隐含了对列表做原处修改。和s=s+[3]完全不一样的。>>> s[1, 2, 3]>>>

The form of a Python assignment statement

Related Article

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.