Compared with other programming languages , What is Python Unique features ? Many programmers will say , Indent . You bet , Indentation is Python The symbolic features of language , But it's just external 、 In form . From the aspect of language characteristics ,Python What are the characteristics of ? I tried to search on Zhihu , The most representative answers are Grammatical simplicity 、 Easy to learn 、 Code efficiency 、 Powerful And so on . Savor these four items carefully , I still think , This is a Python The effect or user feeling of language , It's still not a feature of language features .
Another way , Is it Python What linguistic features of the language make people generally believe that Python With concise grammar 、 Easy to learn 、 Code efficiency 、 Powerful features ? I personally think , Thanks to the list (list)、 Dictionaries (dict)、 Tuples (tuple) And collection (set) this “ Four King Kong ”. Despite the integer (int)、 floating-point (float) And string (str) It's also important. , But these three objects are relative to other programming languages , The difference is not like “ Four King Kong ” So obvious . It is no exaggeration to say , list 、 Dictionaries 、 Tuples and sets represent Python The core and foundation of language , It's also Python The essence of . Learn to use lists 、 Dictionaries 、 Tuples and sets , It means mastering Python This programming language .
If you accept this view , that ,Python The essence of this is from the list 、 Dictionaries 、 Tuples and sets, etc “ Four King Kong ”, It evolved into square brackets 、 It's made up of curly brackets and round brackets “ Bracket family ”.
Square brackets are the first symbol of almost all programming languages . The first one here , It's not about the frequency of use , It refers to the meaning and creativity of programming language shown by this symbol . in fact , In terms of the frequency of use of symbols , Square brackets may also come first —— It's just my intuition , There is no statistical support for .
For beginners , The most common way to create a list is to use square brackets .
>>> a = []
>>> a
[]
>>> b = [3.14, False, 'x', None]
>>> b
[3.14, False, 'x', None]
Even old birds , You also use a lot of square brackets to create lists , Especially when you use derivation to create lists .
>>> c = [i**2 for i in range(5)]
>>> c
[0, 1, 4, 9, 16]
But I always felt , Square brackets are like colloquial or slang , Too casual . I prefer to use rigorous list() To create a list . Use list() Create a list of , yes list The standard method of instantiation of a class , You can feel list How does the constructor of a class adapt to different types of parameters .
>>> a = list()
>>> a
[]
>>> b = list((3.14, False, 'x', None))
>>> b
[3.14, False, 'x', None]
>>> c = list({
1,2,3})
>>> c
[1, 2, 3]
>>> d = list({
'x':1,'y':2,'z':3})
>>> d
['x', 'y', 'z']
>>> e = list(range(5))
>>> e
[0, 1, 2, 3, 4]
>>> f = list('*'*i for i in range(5))
>>> f
['', '*', '**', '***', '****']
Square brackets create lists , But square brackets are not the same as lists , Because square brackets are also used for indexing .
>>> [3.14, False, 'x', None][2]
'x'
>>> [3.14, False, 'x', None][-2]
'x'
>>> [3.14, False, 'x', None][1:]
[False, 'x', None]
>>> [3.14, False, 'x', None][:-1]
[3.14, False, 'x']
>>> [3.14, False, 'x', None][::2]
[3.14, 'x']
>>> [3.14, False, 'x', None][::-1]
[None, 'x', False, 3.14]
The index of the list is very flexible , In particular, the introduction of negative index , use -1 Represents the last element or reverse order , It's a big rush . Operation above , It belongs to the common index mode , If you can read the following code , It means that you have enough skill .
>>> a = [3.14, False, 'x', None]
>>> a[2:2] = [1,2,3]
>>> a
[3.14, False, 1, 2, 3, 'x', None]
For the list object method, if you can use it at your fingertips , That's it Python Master .
>>> a = [3.14, False, 'x', None]
>>> a.index('x')
2
>>> a.append([1,2,3])
>>> a
[3.14, False, 'x', None, [1, 2, 3]]
>>> a[-1].insert(1, 'ok')
>>> a
[3.14, False, 'x', None, [1, 'ok', 2, 3]]
>>> a.remove(False)
>>> a
[3.14, 'x', None, [1, 'ok', 2, 3]]
>>> a.pop(1)
'x'
>>> a
[3.14, None, [1, 'ok', 2, 3]]
>>> a.pop()
[1, 'ok', 2, 3]
>>> a
[3.14, None]
Curly brackets represent dictionary objects , Most beginners think so . However , This is wrong , At least one-sided . In the following code ,a and b They're all objects created with curly braces , But one is a dictionary , One is a collection .
>>> a = {
}
>>> a
{
}
>>> b = {
'x','y','z'}
>>> b
{
'y', 'z', 'x'}
>>> type(a)
<class 'dict'>
>>> type(b)
<class 'set'>
original ,Python Use curly brackets to represent dictionary and collection objects : The curly brackets are empty , Or key value pairs , A dictionary ; There are no repeating elements in curly brackets , Represents a collection . In order not to cause misunderstanding , I used to dict() To generate a dictionary , use set() To generate collections .
>>> dict()
{
}
>>> dict({
'x':1, 'y':2, 'z':3})
{
'x': 1, 'y': 2, 'z': 3}
>>> dict((('x',1), ('y',2), ('z',3)))
{
'x': 1, 'y': 2, 'z': 3}
>>> dict.fromkeys('xyz')
{
'x': None, 'y': None, 'z': None}
>>> dict.fromkeys('abc', 0)
{
'a': 0, 'b': 0, 'c': 0}
>>> set((3,4,5))
{
3, 4, 5}
>>> set({
'x':1, 'y':2, 'z':3})
{
'y', 'z', 'x'}
>>> set([3,3,4,4,5,5])
{
3, 4, 5}
In coding practice , Although in some cases sets are irreplaceable , But the frequency of the set is “ Four King Kong ” The lowest of all , We don't have a discussion here , Just talk about the use of dictionaries .
Py2 Time ,dict The object used to have has_key() Methods , Used to determine whether a key is included .py3 Abandoned this method , Determine whether a key exists in the dictionary , Only use in In this way .
>>> a = dict({
'x':1, 'y':2, 'z':3})
>>> 'x' in a
True
>>> 'v' in a
False
Many people like to assign a key to a dictionary , Add a new key to the dictionary or update the key value .
>>> a = dict()
>>> a['name'] = 'xufive'
>>> a
{
'name': 'xufive'}
I don't recommend this way , Use update() It's more ritualistic , You can also add or modify multiple keys at once .
>>> a = dict()
>>> a.update({
'name':'xufive', 'gender':' male '})
>>> a
{
'name': 'xufive', 'gender': ' male '}
a[‘age’] It's the most common way , But there are also exceptions where the key does not exist . The following method is worth recommending .
>>> a.get('age', 18)
18
dict Class provides keys()、values() and items() The three methods return all the keys of the dictionary respectively 、 All value and all key value pairs . It should be noted that , The returned result is not a list , It's an iterator . If you need to return results in tabular form , Please use list() transformation .
>>> a = dict()
>>> a.update({
'name':'xufive', 'gender':' male '})
>>> list(a.keys())
['name', 'gender']
>>> list(a.values())
['xufive', ' male ']
>>> list(a.items())
[('name', 'xufive'), ('gender', ' male ')]
When traversing the dictionary , Many students have written it as traversal dictionary keys(). Actually , It doesn't need to be that much trouble , You can traverse directly as follows .
>>> a = dict([('name', 'xufive'), ('gender', ' male ')])
>>> for key in a:
print(key, a[key])
name xufive
gender male
Parentheses represent tuple objects , So there should be no problem ? You bet , It doesn't sound like a problem , But in the use of tuples , I believe every beginner will fall into the same pit at least once .
Tuples are not used for the most salient feature of lists , The value of the element cannot be updated . Forget or ignore this , It's going to go into the pit .
>>> a = (3, 4)
>>> a[0] = 5
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
a[0] = 5
TypeError: 'tuple' object does not support item assignment
It has been used for many years Python after , Write the worst I ever had bug, This is the following code .
>>> import threading
>>> def do_something(name):
print('My name is %s.'%name)
>>> th = threading.Thread(target=do_something, args=('xufive'))
>>> th.start()
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
TypeError: do_something() takes 1 positional argument but 6 were given
I clearly only provided 1 Parameters , But the hint is that it gives 6 Parameters , Why? ? original , When tuples are initialized , If there is only a single parameter , You must add a comma after a single parameter (,), otherwise , The initialization result only returns the original parameter .
>>> a = (5)
>>> a
5
>>> type(a)
<class 'int'>
>>> b = ('xyz')
>>> b
'xyz'
>>> type(b)
<class 'str'>
>>> a, b = (5,), ('xyz',)
>>> a, b
((5,), ('xyz',))
>>> type(a), type(b)
(<class 'tuple'>, <class 'tuple'>)
When formatting the output string ,C Language style is my favorite . When there is more than one % When matching is required , The following is perhaps the most natural way to write .
>>> args = (95,99,100)
>>> '%s: Chinese language and literature %d branch , mathematics %d branch , English %d branch '%(' Tianyuan prodigal son ', args[0], args[1], args[2])
' Tianyuan prodigal son : Chinese language and literature 95 branch , mathematics 99 branch , English 100 branch '
Right is right , But it's not good enough . The full score should be like this .
>>> args = (95,99,100)
>>> '%s: Chinese language and literature %d branch , mathematics %d branch , English %d branch '%(' Tianyuan prodigal son ', *args)
' Tianyuan prodigal son : Chinese language and literature 95 branch , mathematics 99 branch , English 100 branch '
Since the element of the tuple is immutable , So why use tuples ? Isn't it more convenient to use lists instead of tuples ? indeed , In most cases , You can use lists instead of tuples , But the following example proves that , Lists can't replace tuples .
>>> s = {
1,'x',(3,4,5)}
>>> s
{
1, (3, 4, 5), 'x'}
>>> s = {
1,'x',[3,4,5]}
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
s = {
1,'x',[3,4,5]}
TypeError: unhashable type: 'list'
We can add tuples to the set , But lists don't work , Because the list is not hashable (unhashable) Of . It's not difficult to understand that : List elements can be changed dynamically , So there is no fixed hash value —— This conflicts with the element uniqueness required by the set ; Elements of tuples are not allowed to be updated , Its hash value does not change throughout its life cycle , So it can be an element of a collection .
obviously , Tuples and lists are stored in a completely different way . Because you don't have to think about updates , Tuples are much faster than lists . Tuples are preferred , Should be Python A basic principle that programmers follow .