The basic foundation of data types Overview Python3

In this paper, the basic data types for Python3 example introduction, these are the necessary knowledge for Python beginners, as follows:

First of all, Python is no need to declare variables. Each variable must be assigned before use variable assignment after the variable will be created. In Python, a variable is a variable, it is not the type we call "type" is the type of objects in memory within the meaning of the variables. Python 3 in six standard data types: Numbers (numbers), String (String), List (lists), Tuple (tuple), Sets (set), Dictionaries (dictionary)

This paper first describes the connections and differences between these types of data types and their definitions.

A, Numbers

Python 3 supports int, float, bool, complex (plural). Numeric types of assignments and calculations are very intuitive, like most languages. Built-in type () function can be used to query object type variable points.

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

Numerical calculation:

>>> 5 + 4 # 加法
9
>>> 4.3 - 2 # 减法
2.3
>>> 3 * 7 # 乘法
21
>>> 2 / 4 # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余 
2
>>> 2 ** 5 # 乘方
32

Highlights:

1, Python may for multiple variable assignments, such as a, b = 1, 2.
2, a variable may be directed by assigning different types of objects.
3, the division value (/) always returns a floating point number, to obtain an integer // operator use.
4, upon mixing calculations, Pyhton integer will be converted into float.

Two, Strings

The Python string str single quotation marks ( '') or double quotes ( "") enclose, while the backslash () escape special characters.

>>> s = 'Yes,he doesn\'t'
>>> print(s, type(s), len(s))
Yes,he doesn't <class 'str'> 14

If you do not want the backslash escape occurs, you can add a r in front of the string that represents the original string:

>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name

Further, as a backslash line continuation character, it indicates the next line is a continuation line. You can also use "" "..." "" or '' '...' '' span multiple lines.

The string can be connected string operator + or operator repeated with *:

>>> print('str'+'ing', 'my'*3)
string mymymy

The Python indexing two strings, the first from left to right, sequentially increases from 0; the second is from right to left successively reduced starting from -1. Note that no separate character type is a character string of length 1.

>>> word = 'Python'
>>> print(word[0], word[5])
P n
>>> print(word[-1], word[-6])
n P

Slicing string can also obtain some substrings. Two indexes separated by a colon, in the form of a variable [head index: Tail index]. Range is taken before and after the opening and closing, and two indexes can be omitted:

>>> word = 'ilovepython'
>>> word[1:5]
'love'
>>> word[:]
'ilovepython'
>>> word[5:]
'python'
>>> word[-10:-6]
'love'

The difference is that the C string, Python strings can not be changed. Assigning a value to an index location, such as word [0] = 'm' will cause an error.

Highlights:

1, can be used to escape the backslash, backslash escapes allow the use of r can not occur.
2, the + operator strings can be connected together, with the * operator repeats.
3, Python strings have two indexing methods, starting with 0 from left to right, right to left to begin -1.
4, the string can not be changed in Python.

Three, List

List (list) is the most frequently used Python data types. The list is written between square brackets, comma-separated list of elements. Type elements in the list may not be the same:

>>> a = ['him', 25, 100, 'her'] 
>>> print(a, type(a), len(a))
['him', 25, 100, 'her'] <class 'list'> 4

And like strings, the list can also be indexed and slice, slice after the list is returned to a new list comprising desired elements. Detailed not go into details here.

The list also supports operating in series, using the + operator:

>>> a = [1, 2, 3, 4, 5]
>>> a + [6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

And Python string is different, elements in the list can be changed:

>>> a = [1, 2, 3, 4, 5, 6]
>>> a[0] = 9
>>> a[2:5] = [13, 14, 15]
>>> a
[9, 2, 13, 14, 15, 6]
>>> a[2:5] = []  # 删除
>>> a
[9, 2, 6]

List built there are many ways, such as append (), pop (), etc., which will be mentioned later.

Highlights:

1, List written between square brackets, elements separated by commas.
2, and the same string, list can be indexed and sliced.
3, List can be spliced using the + operator.
4, List the elements can be changed.

Four, Tuple

Tuple (tuple) and a list of similar, except that the elements of the tuple can not be modified. Tuple is written between parentheses, with a comma-separated list of elements. Tuple element type may not be the same:

>>> a = (1991, 2014, 'physics', 'math')
>>> print(a, type(a), len(a))
(1991, 2014, 'physics', 'math') <class 'tuple'> 4

Similarly tuple string, can be indexed and labeled index from 0 at the start, can also be taken / slicing (see above, is omitted here). In fact, we can put a string of yuan as a special group.

>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0], tup[1:5])
1 (2, 3, 4, 5)
>>> tup[0] = 11 # 修改元组元素的操作是非法的

Although the tuple elements can not be changed, but it can contain a variable object, such as a list of list.
Structure contains zero or one element tuple is a special issue, so there are some additional syntax rules:

tup1 = () # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号

Further, tuple supports use the + operator:

>>> tup1, tup2 = (1, 2, 3), (4, 5, 6)
>>> print(tup1+tup2)
(1, 2, 3, 4, 5, 6)

tring, list and tuple belongs Sequence (sequence).

Highlights:

1, and the string like element of the tuple can not be modified.
2, a tuple can be indexed and sliced, as a method.
3, note that a special syntax rules configured tuple contains 0 or 1 elements.
4, a tuple can be spliced using the + operator.

Five, Sets

Collection (set) is a set of unordered elements will not be repeated. The basic function is to test the relationship between the members and the elimination of duplicate elements. Braces may be used or set () function creates a collection set, note: Create an empty set must be set () instead of {}, {} as is used to create an empty dictionary.

>>> student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
>>> print(student)  # 重复的元素被自动去掉
{'Jim', 'Jack', 'Mary', 'Tom', 'Rose'}
>>> 'Rose' in student # membership testing(成员测试)
True
>>> # set可以进行集合运算
... 
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'a', 'b', 'c', 'd', 'r'}
>>> a - b   # a和b的差集
{'b', 'd', 'r'}
>>> a | b   # a和b的并集
{'l', 'm', 'a', 'b', 'c', 'd', 'z', 'r'}
>>> a & b   # a和b的交集
{'a', 'c'}
>>> a ^ b   # a和b中不同时存在的元素
{'l', 'm', 'b', 'd', 'z', 'r'}

Highlights:

1, set in the collection of elements is not repeated, it will automatically remove repeated.
2, set collection can use braces or set () function to create, but you must use an empty set set () function to create.
3, set collection can be used for members of the test, eliminate duplicate elements.

六、Dictionaries

Dictionary (dictionary) is another very useful Python's built-in data types. Is a type of dictionary mapping (mapping type), which is a random key: value pairs. Keywords must use immutable types, that list and tuple contains the variable types can not do a keyword. In the same dictionaries, the key must be different from each other. >>> dic = {} # create an empty dictionary

>>> tel = {'Jack':1557, 'Tom':1320, 'Rose':1886}
>>> tel
{'Tom': 1320, 'Jack': 1557, 'Rose': 1886}
>>> tel['Jack']  # 主要的操作:通过key查询
1557
>>> del tel['Rose'] # 删除一个键值对
>>> tel['Mary'] = 4127 # 添加一个键值对
>>> tel
{'Tom': 1320, 'Jack': 1557, 'Mary': 4127}
>>> list(tel.keys()) # 返回所有key组成的list
['Tom', 'Jack', 'Mary']
>>> sorted(tel.keys()) # 按key排序
['Jack', 'Mary', 'Tom']
>>> 'Tom' in tel    # 成员测试
True
>>> 'Mary' not in tel # 成员测试
False

Dict constructor () constructed from the sequence of key-value dictionary, of course, also be derived, as follows

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'jack': 4098, 'sape': 4139, 'guido': 4127}
 
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
 
>>> dict(sape=4139, guido=4127, jack=4098)
{'jack': 4098, 'sape': 4139, 'guido': 4127}

Further, there are some types of dictionaries built-in functions, such as clear (), keys (), values ​​() and the like.

Highlights:

1, it is a dictionary mapping type, whose elements are pairs.
2, the dictionary of keywords must be immutable and can not be repeated.
3. Create empty dictionary using {}
, our new learning Python buckle qun: 913066266, look at how seniors are learning! From basic web development python script to, reptiles, django, data mining, etc. [PDF, actual source code], zero-based projects to combat data are finishing. Given to every little python partner! Every day, Daniel explain the timing Python technology, to share some of the ways to learn and need to pay attention to small details, click to join our gathering python learner

Published 38 original articles · won praise 13 · views 40000 +

Guess you like

Origin blog.csdn.net/haoxun06/article/details/104505948