Home  >  Article  >  Backend Development  >  The second Python knowledge point compiled for beginners

The second Python knowledge point compiled for beginners

coldplay.xixi
coldplay.xixiforward
2020-11-12 17:08:551674browse

python video tutorial column introduces the second Python basics.

The second Python knowledge point compiled for beginners

#There are four basic Python tutorials in this series, and this article is the second one.

6.2 Tuple

Tuple is very similar to list, but tuple is immutable, that is, tuple cannot be modified. Tuple is defined by items separated by commas in parentheses.

  • Supports indexing and slicing operations
  • You can use in to check whether an element is in a tuple.
  • Empty tuple()
  • Tuple containing only one element ("a",) #Need to add a comma

Advantages: tuple is faster than list Fast; 'write-protect' data that does not need to be modified can make the code safer

tuple and list can be converted to each other, using the built-in functions list() and tuple().

l = [1, 2, 3]
print( l )# [1, 2, 3]t = tuple(l)
print(t) # (1, 2, 3)l = list(t)print (l) #[1, 2, 3]复制代码

The most common use of tuples is in print statements, as in the following example:

name = "Runsen"age = 20print( "Name: %s; Age: %d") % (name, age)# Name: Runsen; Age: 20复制代码

The function is as follows:

  • count(value) 

Returns the number of elements in the tuple whose value is value

t = (1, 2, 3, 1, 2, 3)print (t.count(2) )# 2复制代码
  • index(value, [start, [stop]]) 

Returns the index of the first occurrence of value in the list, if not, an exception occurs ValueError

t = (1, 2, 3, 1, 2, 3)
print( t.index(3) )# 2try:    print (t.index(4))except ValueError as V:
    print(V)  # there is no 4 in tuple复制代码

6.3 Dictionary

Dictionary by key Composed of value pairs, the key must be unique;

eg: d = {key1:value1, key2:value2};

The empty dictionary is represented by {}; dictionary The key-value pairs in are not in order. If you want a specific order, you need to sort them before use;

d[key] = value, if it already exists in the dictionary key, then assign it the value value, otherwise add a new key-value pair key/value;

use del d [key] You can delete key-value pairs; to determine whether there is a key in the dictionary, you can use in or not in;

d = {}
d["1"] = "one"d["2"] = "two"d["3"] = "three"del d["3"]for key, value in d.items():    print ("%s --> %s" % (key, value))#1 --> one#2 --> two复制代码

The dict function is as follows:

  • clear() 

Delete all elements in the dictionary

d1 = {"1":"one", "2":"two"}
d1.clear()print (d1 )# {}复制代码
  • copy() 

Return a copy of the dictionary (shallow copy )

d1 = {"1":"one", "2":"two"}
d2 = d1.copy()
print( d2 )#{'1': 'one', '2': 'two'}print(d1 == d2) # Trueprint(d1 is d2) # False复制代码

Shallow copy values ​​are the same, but the objects are different and the memory addresses are different.

  • dict.fromkeys(seq,val=None)

Create and return a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and val is all the keys of the dictionary Corresponding initial value (default is None)

l = [1, 2, 3]
t = (1, 2, 3)
d3 = {}.fromkeys(l)print (d3) #{1: None, 2: None, 3: None}d4 = {}.fromkeys(t, "default")
print(d4) #{1: 'default', 2: 'default', 3: 'default'}复制代码
  • get(key,[default]) 

Returns the corresponding value of the key key in the dictionary dict, if it does not exist in the dictionary If this key is used, the default value is returned (the default value is None)

d5 = {1:"one", 2:"two", 3:"three"}print (d5.get(1) )#oneprint (d5.get(5)) #Noneprint (d5.get(5, "test") )#test复制代码
  • has_key(key) 

Determine whether there is a key key in the dictionary

d6 = {1:"one", 2:"two", 3:"three"}
print( d6.has_key(1) ) #Trueprint (d6.has_key(5))  #False复制代码
  • items() 

Returns a list containing tuples of (key, value) pairs in the dictionary

d7 = {1:"one", 2:"two", 3:"three"}for item in d7.items():    print (item)#(1, 'one')#(2, 'two')#(3, 'three')for key, value in d7.items():    print ("%s -- %s" % (key, value))#1 -- one#2 -- two#3 -- three复制代码
  • keys() 

Returns a list containing all the keys in the dictionary

d8 = {1:"one", 2:"two", 3:"three"}for key in d8.keys():    print (key)#1#2#3复制代码
  • values() 

Returns a list containing all the values ​​in the dictionary

d8 = {1:"one", 2:"two", 3:"three"}for value in d8.values():
    print( value)#one#two#three复制代码
  • pop(key, [default]) 

If the key key exists in the dictionary, delete it and return dict[key]. If it does not exist and no default value is given, a KeyError exception is raised.

d9 = {1:"one", 2:"two", 3:"three"}print (d9.pop(1) )#oneprint( d9) #{2: 'two', 3: 'three'}print( d9.pop(5, None)) #Nonetry:
    d9.pop(5)  # raise KeyErrorexcept KeyError, ke:    print ( "KeyError:", ke) #KeyError:5复制代码
  • popitem() 

Delete any key-value pair and return the key-value pair. If the dictionary is empty, an exception KeyError

d10 = {1:"one", 2:"two", 3:"three"}print (d10.popitem() ) #(1, 'one')print (d10)  #{2: 'two', 3: 'three'}复制代码
## will be generated.
    #setdefault(key,[default]) 
If there is a key in the dictionary, the vlaue value is returned. If there is no key, the key is added. The value is default, and the default is None

d = {1:"one", 2:"two", 3:"three"}print (d.setdefault(1))  #oneprint (d.setdefault(5))  #Noneprint( d)  #{1: 'one', 2: 'two', 3: 'three', 5: None}print (d.setdefault(6, "six")) #sixprint (d)  #{1: 'one', 2: 'two', 3: 'three', 5: None, 6: 'six'}复制代码
    update(dict2)
Add the elements of dict2 to dict. Repeated keys will overwrite the key values ​​in dict

d = {1:"one", 2:"two", 3:"three"}
d2 = {1:"first", 4:"forth"}

d.update(d2)print (d)  #{1: 'first', 2: 'two', 3: 'three', 4: 'forth'}复制代码
    viewitems() 
Returns a view object, a list of (key, value) pairs, similar to a view. The advantage is that if the dictionary changes, the view will change simultaneously. exist During the iteration process, the dictionary is not allowed to change, otherwise an exception will be reported

d = {1:"one", 2:"two", 3:"three"}for key, value in d.viewitems():    print ("%s - %s" % (key, value))#1 - one#2 - two#3 - three复制代码
    viewkeys() 
Returns a view object, a list of keys

d = {1:"one", 2:"two", 3:"three"}for key in d.viewkeys():
    print( key)#1#2#3复制代码
    viewvalues() 
Returns a view object, a list of values

d = {1:"one", 2:"two", 3:"three"}for value in d.viewvalues():    print (value)#one#two#three复制代码
6.4 Sequence

The sequence type means that the elements in the container start from 0 Indexed sequential access allows access to one or more elements at a time; lists, tuples, and strings are all sequences. The three main characteristics of sequences are

    Index operators and slicing operators
  • Indexing can get specific elements
  • Slicing can get part of the sequence

Index operator and slice operator

numbers = ["zero", "one", "two", "three", "four"]  
print (numbers[1] )# oneprint (numbers[-1] )# four#print( numbers[5]) # raise IndexErrorprint (numbers[:]) # ['zero', 'one', 'two', 'three', 'four']print (numbers[3:]) # ['three', 'four']print (numbers[:2]) # ['zero', 'one']print (numbers[2:4] )# ['two', 'three']print (numbers[1:-1] )# ['one', 'two', 'three'] 复制代码
The first number in the slice operator (before the colon) indicates the position where the slice starts, and the second number (after the colon ) indicates where the slice ends.

If you do not specify the first number, Python will start from the beginning of the sequence. If the second number is not specified, Python will stop at the end of the sequence.

Note that the returned sequence starts from the start position and ends just before the end position. That is, the starting position is included in the sequence slice, while the ending position is excluded from the slice. Slicing can be done with negative numbers. Negative numbers are used starting from the end of the sequence.

Related free learning recommendations: python video tutorial

The above is the detailed content of The second Python knowledge point compiled for beginners. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete