Whether it's doing scientific computing or writing applications , You need to use some basic data structures , Such as the list , Tuples , Dictionary, etc .
This article will explain in detail Python These basic data structures in .
The list is list, It can be expressed in square brackets :
In [40]: ages = [ 10, 14, 18, 20 ,25] In [41]: ages Out[41]: [10, 14, 18, 20, 25]
list There are some very useful ways , such as append,extend,insert,remove,pop,index,count,sort,reverse,copy etc. .
for instance :
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] >>> fruits.count('apple') 2 >>> fruits.count('tangerine') 0 >>> fruits.index('banana') 3 >>> fruits.index('banana', 4) # Find next banana starting a position 4 6 >>> fruits.reverse() >>> fruits ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] >>> fruits.append('grape') >>> fruits ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape'] >>> fruits.sort() >>> fruits ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] >>> fruits.pop() 'pear'
The stack is characterized by last in, first out , And the list gives us append and pop Method , So it's very easy to use lists to implement stacks :
>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4]
The queue is characterized by first in, first out , But using lists to insert elements at the head of a queue is slow , Because you need to move all the elements .
We can use collections.deque
To quickly operate from both ends :
>>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])
To create a list , The usual practice is to use for loop , To traverse the list , And set a value for it :
>>> squares = [] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Or we can use list derivation to generate lists more concisely :
squares = [x**2 for x in range(10)]
The structure of list derivation is the following content contained in a square bracket : An expression , Followed by a for
Clause , Then there are zero or more for
or if
Clause .
The list derivation will traverse for The elements of a sentence , And use expressions to evaluate , Return the generated element as a new list element .
Look at a more complicated :
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
The above expression is equivalent to :
>>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List derivations can also be nested , If we have a matrix :
>>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ]
You can use the following expression to exchange the matrix between rows and columns :
>>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Or use a simpler one zip function :
>>> list(zip(*matrix)) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
To delete an element from a list, you can use del.del You can delete a specific value from the list , You can also delete slices , Even delete the entire list :
>>> a = [-1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5] >>> del a[:] >>> a [] >>> del a
Tuples are very similar to lists , The difference is that tuples are immutable .
Tuples are represented by parentheses , Or you don't have to use parentheses .
>>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') >>> # Tuples may be nested: ... u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Tuples and List It's very similar to , There are slicing and indexing operations .
Tuples can be easily unpacked :
>>> x, y, z = t
Use together set Functions or curly braces .
The elements in a collection are not repetitive , This point is related to java Medium set Is very similar .
Because the dictionary representation is also curly braces , So if you need to create an empty collection , Need to use set, Because it's empty {} It's a dictionary .
Look at some simple examples of collections :
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been removed {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'}
Just like the list , Sets also support derivation :
>>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'r', 'd'}
Dictionaries are also represented by curly braces , The difference is that the elements in the dictionary are based on key:value In the form of .
Here are some basic operations of the dictionary :
>>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'jack': 4098, 'sape': 4139, 'guido': 4127} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'jack': 4098, 'guido': 4127, 'irv': 4127} >>> list(tel) ['jack', 'guido', 'irv'] >>> sorted(tel) ['guido', 'irv', 'jack'] >>> 'guido' in tel True >>> 'jack' not in tel False
Except for the curly brackets , You can also use dict Function to build a dictionary :
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'guido': 4127, 'jack': 4098}
If the keyword is a simple character , You can write this directly :
>>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'guido': 4127, 'jack': 4098}
The same derivation can be used :
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36}
We usually use for Statement to traverse a collection or dictionary ,list etc. .
When we traverse the dictionary , have access to items() Method to get key and value:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
If it's a list , Then you can use enumerate Function to get index and value:
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
We used it before zip function ,zip Function can match elements in multiple sequences one by one :
>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.
This article has been included in http://www.flydean.com/06-python-data-structure/ The most popular interpretation , The deepest dry goods , The most concise tutorial , There are so many tricks you don't know about waiting for you to discover ! Welcome to my official account. :「 Program those things 」, Know technology , Know you better !