The sequence is the most basic data structure in Python. Each element in the sequence is assigned a number-its position, or index, the first index is 0, the second index is 1, and so on. Python has 6 built-in types of sequences, but the most common are lists and tuple tuples. Sequences can be performed by operations including indexing, slicing, adding, multiplying, and checking members. In addition, Python has built-in methods for determining the length of a sequence and determining the maximum and minimum elements. A list is the most commonly used Python data type and can appear as a comma-separated value within a square bracket. The list's data items do not need to have the same type, creating a list, as long as the different data items separated by commas are enclosed in square brackets.
1, List
Python's built-in data types, ordered collections, and additions and deletions at any time . Can contain different data types: integer, floating-point, String, list, tuple, dict, set, bool, NULL, constant
list1=[1.2, 2.1, 3, 3.2, 5, ' a ', (2, 2, 3), [1.2, 2], {1:2, 2:3}, set ([2, 3, 2.2]), 3.14, None]
Empty list: list1=[]; List2=list ()
function: Len (), append (), remove () removes the first occurrence of a value in the list, insert (), pop (), sort (), Del, list (), reverse (), index () Find the index position of the first occurrence of a value from the list, count () counts the number of occurrences of an element in the list, extend () appends multiple values from another sequence at the end of the list (the original list is expanded with a new list)
Delete: Del list1[0]
Ganso Convert to List: Tuple-->list list (tuple)
Append (value) adds the element to the end, insert (i,value) adds the element to any position, POPs () removes the end element, POPs (i) deletes the element at the specified position, and remove (value) deletes the element value directly; List1.sort ( ) to sort the elements
Value: List1[0], list1[4:], list1[:-4], list1[2:-3]
Nested: List inside can be nested list to form similar to two-dimensional, three-dimensional, multidimensional array of Dongdong, list1[1][2]/list1[2][3][3][5] ...
Modify: Modify the value of a location element list1[i]=value
2. Tuple Ganso
Python has built-in data types that have sequence lists that cannot be modified once initialized . The tuple is immutable, so the code is more secure. Can contain different data types: integer, floating-point, String, list, tuple, dict, set, bool, NULL, constant
Empty Ganso: tuple1= (); Tuple2=tuple ()
function: Len (), del delete entire tuple, tuple () convert list to Ganso/append (), remove (), insert (), pop (), sort ()
Value: Tuple1[0], tuple1[-1], tuple1[3:], tuple1[:-1], tuple1[2:-2]
Represents: Empty tuple1= (); an element tuple1= (2,) followed by a comma
Although the tuple is immutable, the list, Dict, and set inside it can be changed.
Create:Tup1= (' Physics ',' Chemistry ',1997,2000 tup2 = ( 1, 2 3, 4, 5 ); = "a" "B" , "C" Span class= "pun" >, "D" ;
Operators: (1, 2, 3) + (4, 5, 6), (' hi! ',) * 4, 3 in (1, 2, 3), for x in (1, 2, 3): Print x,
3. Dict Dictionaryd={‘Michael‘: 95, ‘Bob‘: 75, ‘Tracy‘: 85}
Python built-in, key-value pair (key-value) storage, Find Fast ; Dict key must be an immutable object (string, number, Ganso); value can contain different data types: integers, floating-point numbers, strings, lists, Tuple, Dict, set, bool, NULL, constant
Empty dictionary: dict1={}; Dict2=dict ()
function: Len (), Get (), Pop (), Del, Has_key (), items (), keys (), values (), update (), append (), remove (), insert (), sort ()
Value: d[' Michael ']
Assignment: d[' Michael ']=100
Added: d[' Jim ']=22
Delete: Pop (' Tracy '); Del d[' Jim '];del D
Determine if key exists: ' Tracy ' in D; D.get (' Tracy ') if key does not exist, returns none; D.get (' Tracy ', value) if key does not exist, return the value specified by itself
Compared with list, Dict has the following features:
- The speed of finding and inserting is very fast and will not increase with the increase of key;
- It takes a lot of memory, and it wastes a lot of memory.
And the list is the opposite:
- The time to find and insert increases as the element increases;
- Small footprint and little wasted memory.
So, Dict is a way of exchanging space for time.
Dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object .
This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating the position by key is called the hash Algorithm (hash).
To ensure the correctness of the hash, the object as a key can not be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is mutable and cannot be a key
4, set unordered set, key does not repeat
No index, no slices, and as an unordered collection, set does not record the element position or insertion point. Therefore, set does not support operation of indexing, slicing, or other class sequence (Sequence-like)
Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.
To create a set, you need to provide a list as the input collection:
s = set([1, 2, 3]):set([1,2,3])
s = set (' Boy '): Set ([' B ', ' o ', ' y '])
s = set (' cmd ', ' pid '): Set ([' cmd ', ' pid '])
s = {' txt ', ' png ', ' jpg ', ' xls ', ' csv ', ' zip ', ' xlsx ', ' gif ', ' gif '}
Empty collection: Set1 = set ();
Functions: Pop (), add (), remove (), update (), Len (), clear (), discard (), append (), insert (), sort ()
Add to:add(key)、update();区别 s.add(‘boy‘):set([‘boy‘,1,2,3]);s.update(‘boy‘):set([‘boy‘,‘b‘,1,2,3,‘o‘,‘y‘]);s.update([23,22,32])添加多项
Delete:remove(key)删除指定位置的元素,如果不存在,引发KeyError;pop()删除并且返回集合“s”中的一个不确定的元素, 如果为空则引发 KeyError;clear()删除所有元素;s.discard(x),如果在 set “s”中存在元素 x, 则删除
Intersection: Set1 & Set2 (Set1.intersection (Set2)) Two set of common elements
Set: Set1 | Set2 (Set1.union (Set2)) Two set elements are added and then de-weighed
Difference set: Set1-set2 (Set1.difference (Set2)) Set Set1 Remove and same part as set Set2
Symmetric differential set: Set1^set2 (Set1.symmetric_difference (Set2)) items in Set1 or Set2, but not both
Operation: Key in Set1; Key not in Set1; for key in Set1;
Set1.issubset (Set2) is equivalent to Set1<=set2: Tests whether each element in the Set1 is in Set2
Set1.issuperset (Set2) is equivalent to Set1>=set2: Tests whether each element in the Set2 is in Set1
S.copy () returns a shallow copy of the set "s"
The only difference between set and dict is that it does not store the corresponding value, but the set principle is the same as the dict, so it is also not possible to put mutable objects, because it is not possible to determine whether the two Mutable objects are equal, and there is no guarantee that there will be no duplicate elements inside the set. Try putting the list in set to see if it will give an error
Repeating elements are automatically filtered in set
Application Example: How to remove the duplicate elements in the mass list:
A = [one, one, one, one, one, one]
A = List (set (a)): [33, 11, 44, 22]
Summary: 1, list, tuple is a sequence table; dict, set is unordered list
2, List element variable, tuple element is not variable
3, Dict and set key value is immutable, uniqueness
4. Set only key does not have value
5, set of use: Go to weight, and set, intersection, etc.
6. List, tuple:+, *, index, slice, check member, etc.
7, dict query efficiency is high, but consumes more memory; list, tuple queries inefficient, but consumes less memory
The difference between list/tuple/dict/set in Python