python and the common variable data types

About versions and characteristics of the installation and the concept can refer to the python Bowen, python language foundation

This blog post focuses on the following issues:
a, python variables
two, python commonly used data types

First, what is python variables?

Variable is an area of ​​computer memory, can store any variable value, and the value can be changed. Variable names consist of letters, digits, and underscores. Note that you can not use python keywords, English case-sensitive letters, first character must be a letter or an underscore, not a number, sample code as follows:

>>> x=1
>>> _x=2
>>> print(x)
1
>>> print(_x)
2

x _x and are valid variable name, print () is the output function, the output value can be variable, may not use parentheses.

python variables need to be declared, that is the variable assignment variable declaration and definition of the process, i.e. as _x = 2 is declared and defined process. May also be assigned to several variables simultaneously, the following sample code:

>>> a,b,c=4,5,6
>>> print (a)
4
>>> print(b,c)
5 6

a, b, c = 4,5,6 three variables simultaneously to the assignment, simplifies the code of a plurality of variable assignments.

Two, python commonly used data types are there?

python built-in data types are numbers, strings, tuples, lists and dictionaries .

1, Digital

~ Digital types include integer, float, Boolean, etc., when a statement by the python built basic data types to manage variables for values ​​associated with the type, and the conversion program in the background. Automatically determine a variable based on the value of the variable type, the programmer need not be concerned about what type of variable space, just know that variables created to store a number, but this value program operation.

1) int, float,
integer represented as an integer type ~ have to use decimal floating-point represented, the following sample code:

>>> w=123
>>> print(w)
123
>>> w=5.21
>>> print(w)
5.21

Above code first defines a variable w = 123, in this case is an integer value w, w even integer variables, while when w = 5.21, w has become the floating-point variables, it can be seen, the type of the variable to be able to change, and this is Java, C # language is different. This is because when the python to already exist
when a variable assignment again, actually creating a new variable, even if the same variable name, but not the same logo, can be used to identify variables id function output.

>>> w=123
>>> print(id(w))
140709308982112
>>> 
>>> w=5.21
>>> print(id(w))
2193072831584

The above code is the identification of a variable x for printing, before and after the assignment is not the same identifier.

2) Boolean
Boolean logic operation, there are two values True, False, it indicates true and false. Sample code is as follows:

>>> 10>50
False
>>> 
>>> 30>15
True

. 3) python operator
symbol arithmetic operations and mathematical operations used in the python using substantially the same as the +, -, *, /,%, // ***** (addition, subtraction, multiplication, division, modulo, integer I, after power) and the order of operation is small parentheses first subtraction, multiplication and division, the priority parentheses. Sample code is as follows:

>>> x,y=10,2
>>> print(x+y,x-y,x*y,x/y)
12 8 20 5.0
>>> print (2+4*8)
34
>>> print((6+5)*4)
44

The following are two arithmetic operators and ****% (and modulo exponentiation), modulo operation taking the remainder, the result of the exponentiation calculation that multiplies, i.e. power, the following sample code:

>>> 8%5
3
>>> 8%4
0
>>> 2**2
4
>>> 6**3
216
>>> 2**4
16

2, string

Python string type is a group set includes numbers, letters and symbols, using as a whole.

1) using the string
in python string representing the three ways of single and double quotation marks, three marks, the following sample code:

>>> name='王五'
>>> address="长安街"
>>> content='''欢迎来到北京'''
>>> print (name)
王五
>>> print(address)
长安街
>>> print(content)
欢迎来到北京

Variable name to use single quotes, double quotes variable address, variable content using a three quotes, they are legitimate python string type. It should be noted that the role of single and double quotes is the same, may be used in accordance with custom, but defining multiple lines of text, you must use three quotes.

Common escape character follows:
python and the common variable data types

2) Other uses string
string python may be multiplication operations, may be multiplied by an integer number and a string, such as string 3 by using the number "a", the result is the string "aaa", the same as in string "a" is connected to three times, the following sample code:

>>> print(3*'a')
aaa
>>> print (5*'b')
bbbbb

3. List

List (list) is a very important python data type, typically as the return type of the function. By a group of elements, the list can be achieved to add, delete, and search operations, the element values ​​can be changed.

1) the definition of the list
list is a data structure built python, define enclosed within brackets, the elements separated by commas, the following syntax:
python and the common variable data types

2) the list of supported
data list is ordered, the order defined by the line up, the value of a position of the element can be individually removed, syntax is as follows:
python and the common variable data types
the following sample code:

>>> num=['111','222','333']
>>> print(num[0])
111
>>> print(num[1])
222
>>> print(num[2])
333

Defined list num, three strings stored sequence is '111', '222', '333', together with the value in parentheses in parentheses list name num, numeral denotes the index position, the position is to be noted 0 start ascending order.

  • Can get to know the scope of a list of a group of elements, the following syntax:
    python and the common variable data types
    may be output before the start position to the end position of the element, not including the end position, the following sample code:
    >>> num=['111','222','333','444']
    >>> print(num[0:1])
    ['111']
    >>> 
    >>> print(num[0:3])
    ['111', '222', '333']
    >>> print(num[1:2])
    ['222']
    >>> 
    >>> print(num[2:])
    ['333', '444']

    [0: 1] indicates the start of index 0, the index position of the element 1 before, all take only to the first element, [0: 3] can be taken to the element 3 before the index, i.e. the list 1,2,3 elements, the other the same way.

3) Edit list element value
can be modified to specify the location of a list of element value, the syntax is as follows:
python and the common variable data types
the following sample code:

>>> num=['111','222','333','444']
>>> num[0]='001'        #修改
>>> print(num)
['001', '222', '333', '444']

When definition list, the index position of the element 0 is "111", after modifying its value is "001", the element index position 0 becomes "001."

4) Add a list of elements
can add an element to the end of the list, the syntax is as follows:
python and the common variable data types

Sample code is as follows:

>>> num=['111','222','333','444']
>>> print (num)
['111', '222', '333', '444']
>>> num.append('555')       #末尾添加新元素
>>> print (num)
['111', '222', '333', '444', '555']

After use append ( '555'), "555" is added to the end of the list.

  • Insert a new element in the list before the specified position, the syntax is as follows:
    python and the common variable data types
    the following sample code:
    >>> num=['111','222','333','444']
    >>> num.insert(1,'001')
    >>> print(num)
    ['111', '001', '222', '333', '444']

    INSERT statement (1, '001') acting in the index position prior to insertion 1 '001', the index position of the current element 1 is '222', '001' is inserted into the front of it.

5) Remove list elements
can be specified index list of elements, syntax is as follows:
python and the common variable data types
the following sample code:

>>> num=['111','222','333']
>>> del (num[1])
>>> print(num)
['111', '333']

Remove the del element one of '222', the output does not exist in the list num '222' element.

6) Find a list of elements
to use in keywords to find whether the specified value exist in the list, the syntax is as follows:
element values in the list of names
return Boolean True or False
sample code as follows:

>>> num=['111','222','333']
>>> ('111')in num
True
>>> ('444')in num
False

String '111' exists in the list, return True; string '444' does not exist in the list, return False.

7) The combined list
the plurality of lists may be combined using plus, the following sample code:

>>> num1=['111','222']
>>> num2=['333','444']
>>> numAll=(num1+num2)
>>> print(numAll)
['111', '222', '333', '444']
>>> numAll=(num2+num1)
>>> print(numAll)
['333', '444', '111', '222']

It defines two lists num1 and num2, when using the plus merge operation, the back of the list element plus sign appended to the front of the list.

8) Repeat list
asterisk can repeat the list, similar to a single string multiplication operations, the following sample code:

>>> num1=['111','222']
>>> num=(num1*5)
>>> print(num)
['111', '222', '111', '222', '111', '222', '111', '222', '111', '222']

4, tuples

Tuple (tuple) and a list of similar, the python is a data structure of different elements, each element may store different types of data, such as strings, numbers, or even tuple. But tuples can not be amended, that can not make any changes after the operation to create a tuple, tuple usually represents a row of data, and tuple elements represent different data items.

1) Create a tuple of
the tuple is defined by the key parentheses, once created, it can not modify the contents of the tuple, the syntax is defined as follows:
python and the common variable data types
following modifications histogram code added define tuples, the following sample code:

>>>import matplotlib.pyplot as plt
>>> x=(1,9)            #元组
>>> height_all=(6,10)     #元组
>>> width_all=4
>>> title=("cylinder")
>>> plt.bar(x=(1,9),height=(6,10),width=(4))
>>> plt.title(title)
>>> plt.show()

This code can still work properly, and use the list and there is no difference. The biggest difference tuples and lists is that it is write-protected and can not make any changes after creation.
python and the common variable data types

python and the common variable data types
And differences in the use of a list of tuples is not large, so why use a tuple it? Mainly because tuples are immutable, faster than the operation list, and because it can not be modified, the data is more secure, so to decide whether or tuple list, make the program more efficient and rational according to actual situation.

2) Operation tuple
of tuples may be a series of operational elements thereof.

  • Tuple has a non-denaturing, the operation compared to less list, wherein the list of values ​​is identical to the operation, the following sample code:

    >>> num=('111','222','333')
    >>> print (num[0])
    111
    >>> print (num[1])
    222

    与列表的取值操作完全相同,都是使用方括号作为关键字取值。

  • 元素不允许删除元组中的元素值,但是可以删除整个元组,语法如下:
    python and the common variable data types
    示例代码如下:

    >>> num=('111','222','333','444')
    >>> del (num[0])              #删除元素,报错
    Traceback (most recent call last):
    File "<pyshell#219>", line 1, in <module>
    del (num[0])
    TypeError: 'tuple' object doesn't support item deletion
    >>> print (num)
    ('111', '222', '333', '444')
    >>> del (num)              #删除元组后元组不存在,报错
    >>> print (num)
    Traceback (most recent call last):
    File "<pyshell#222>", line 1, in <module>
    print (num)
    NameError: name 'num' is not defined
    >>> 

    定义元组num后,删除某一个元素程序报错。删除整个元组后,在想使用这个元组,编译器会报未定义变量的错误。

  • 元组和列表可以做互相转换操作,元组转换为列表的语法如下:
    python and the common variable data types
    示例代码如下:
    >>> num=('111','222','333','444')      #元组
    >>> listNum =list(num)                  #转换为列表
    >>> print (listNum)
    ['111', '222', '333', '444']
    >>> (listNum[0])='001'                 #修改列表
    >>> print( listNum)
    ['001', '222', '333', '444']
    >>> print (type(num))           #输出元组类型
    <class 'tuple'>
    >>> print (type(listNum))       #输出列表类型
    <class 'list'>

    这段代码首先定义了元组num,然后把它转换为列表listNum,对列表listNum可以做修改元素的操作,使用type()函数输出了元组的列表的类型。

5、字典

字典(dict)是python中重要的数据类型,字典是由“键-值”对组成的集合,字典中的值通过键来引用。

1)字典的创建
字典的每个元素是由“键-值”对(key-value)组成的,键值之间使用冒号分隔,“键-值”对之间用逗号隔开,并且被包含在一对花括号中。键是唯一的,不能存在多个,且它的值是无序的,键可以是数字、字符串、元组,一般用字符串作为键。定义的语法如下:
python and the common variable data types
示例代码如下:

>>> mobile = {'tom':'19991111','bob':'19982222','alice':'19973333'}
>>> print(mobile)
{'tom': '19991111', 'bob': '19982222', 'alice': '19973333'}
>>> print(type(mobile))
<class 'dict'>

定义了一个字典mobile,存储的键是姓名,值是电话号码,他们构成了对应的关系,使用type函数可以查看到它的类型是’dict‘。

2)字典的取值操作
字典的取值与元组和列表有所不同,元组和列表都是通过数字索引获取对应位置的值,而字典是通过键获取对应的值。取值的语法如下:
python and the common variable data types
示例代码如下:

>>> mobile = {'tom':'19991111','bob':'19982222','alice':'19973333'}
>>> print(mobile["tom"])
19991111
>>> print(mobile["bob"])
19982222

分别使用键“tom”“bob”可以获取到他们对应的值。需要注意的是,键是唯一的,而不同键的值却可以相同,当定义多个键相同时,字典中只会保留最后一个定义的键值对,示例代码如下:

>>> mobile = {'tom':'19991111','tom':'1×××222','tom':'19993333'}
>>> print(mobile)
{'tom': '19993333'}

字典中定义了3个“键-值”对,他们的键是相同的,最后输出时只有最后一个定义的“键-值”对存在。

3) add a dictionary, modify, delete operations
dictionary to add new elements only need to be assigned to the new key, key not in the dictionary, it will automatically be added. Sample code is as follows:

>>> mobile = {'tom':'19991111','bob':'19982222'}
>>> (mobile['alice'])='19993333'
>>> print(mobile)
{'tom': '19991111', 'bob': '19982222', 'alice': '19993333'}

Dictionary key 'alice' does not exist when defining, after the assignment, the key 'alice' is added to the dictionary. Dictionary key name key-value pair is case-sensitive.

Modify elements in the dictionary used directly bonds present assignment, the following sample code:

>>> mobile = {'tom':'19991111','bob':'19982222'}
>>> (mobile['bob'])='19993333'
>>> print(mobile)
{'tom': '19991111', 'bob': '19993333'}

Removing elements of the dictionary, the del function has the following syntax:
del name dictionary [ 'key']
the following sample code:

>>> mobile = {'tom':'19991111','bob':'19982222'}
>>> del (mobile['tom'])
>>> print(mobile)
{'bob': '19982222'}

This is the end of this chapter Bowen, thanks for reading

Guess you like

Origin blog.51cto.com/14156658/2429630