Python -- (variable), python -- Variable

Source: Internet
Author: User
Tags element groups

Python -- (variable), python -- Variable

Variable:

Python is a dynamic type language, that is, the type of the variable does not need to be declared in advance. A variable is an object reference. A variable only points a pointer to the memory address of the object. The type and value of the variable are initialized at the moment of value assignment. Variable name: 1. explicit --> easy to understand 2. nums_of_alex_gf = 19 3. numsOfAlexGf = 20 description 4. the hyphen cannot be named as a variable. the number cannot start with, but it can be in the middle or end with 6. special characters cannot be part of the variable name. space is not allowed. the keyword cannot be declared as a variable.

Variable assignment

Variables in Python do not need to be declared. Variable assignment is a process of variable declaration and definition.

Each variable created in the memory contains the variable identifier, name, and data.

Each variable must be assigned a value before it can be used.

Equals sign (=) is used to assign values to variables.

On the left side of the equal sign (=) operator is a variable name, and on the right side of the equal sign (=) operator is the value stored in the variable.

 

Assign values to multiple variables

Python allows you to assign values to multiple variables at the same time. For example:

A = B = c = 1

For the above instance, create an integer object with a value of 1. The three variables are allocated to the same memory space.

You can also specify multiple variables for multiple objects. For example:

A, B, c = 1, 2, "john"

In the above example, the two integer objects 1 and 2 are allocated to variables a and B, and the string object "john" is allocated to the variable c.

Problem:

Now there is a tuples or sequences containing N elements. How can I decompress the values in them and assign values at the same time?
N variables?

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

>>> P = (4, 5) >>> x, y = p >>>> x4 >>> y5 >>>>> data = ['acme ', 50, 91.1, (2012, 12, 21)] >>> name, shares, price, date = data >>> name 'acme '>>> date (2012, 12, 21) >>> name, shares, price, (year, mon, day) = data >>> name 'acme '>>> year2012 >>> mon12 >>> day21 >>>View Code

This unzipping value can be used on any iteratable object, not just lists or tuples.
Including strings, file objects, iterators, and generators.

 

Sometimes, you may only want to extract a part of it and discard other values. In this case, Python does not mention
For special syntax. However, you can use any variable name to place a placeholder, and then you can discard these variables.

>>> Data = ['acme', 50, 91.1, (2012, 12, 21)]
>>> _, Shares, price, _ = data
>>> Shares
50
>>> Price
91.1

Problem:

If the number of elements of an object that can be iterated exceeds the number of variables, A ValueError is thrown. So
How can we extract N elements from this iteratable object?

The asterisk expression in Python can be used to solve this problem.

>>> Record = ('Dave ', 'Dave @ example.com', '2017-555-1212 ', '2017-555-1212 ')
>>> Name, email, * phone_numbers = record
>>> Name
'Dave'
>>> Email
'Dave @ example.com'
>>> Phone_numbers
['2017-555-1212 ', '2017-555-1212']

The asterisk expression can also be used at the beginning of the list. For example, you have a sort of sales data for the first eight months of a company.
Column, but you want to see the comparison between the data of the last month and the average value of the previous seven months. You can do this:
* Trailing_qtrs, current_qtr = sales_record
Trailing_avg = sum (trailing_qtrs)/len (trailing_qtrs)
Return avg_comparison (trailing_avg, current_qtr)
The following is the execution result in the Python Interpreter:
>>> * Trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
>>> Trailing
[10, 8, 7, 1, 9, 5, 10]
>>> Current
3

It is worth noting that the asterisk expression is useful when the iteration element is a sequence of variable long element groups. For example,
The following is a sequence of tuples with tags:
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)

Foo 1 2
Bar hello
Foo 3 4

The asterisks decompression syntax is also useful for string operations, such as string segmentation.

Sample Code:
>>> 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, if you want to extract some elements and discard them, you cannot simply use them *, but you can use
Common obsolete names, such as or ign.
Sample Code:
>>> Record = ('acme', 50,123.45, (12, 18,201 2 ))
>>> Name, * _, (* _, year) = record
>>> Name
'Acme'
>>> Year

2012

In many functional languages, the asterisk extract syntax has many similarities with list processing. For example, if you have
You can easily split a list into two parts:
>>> Items = [1, 10, 7, 4, 5, 9]
>>> Head, * tail = items
>>> Head
1
>>> Tail
[10, 7, 4, 5, 9]
>>>
If you are smart enough, you can use this segmentation syntax to skillfully implement recursive algorithms. For example:
>>> Def sum (items ):
... Head, * tail = items
... Return head + sum (tail) if tail else head
...
>>> Sum (items)
36

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.