[Python Basics 2] Super detailed tutorial for entry-level friends

foreword

Previous article
[Python Basics 1] Super detailed tutorial for entry-level friends

6.2 Tuples

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

  • Supports indexing and slicing operations
  • You can use in to see if an element is in the tuple.
  • empty tuple()
  • A tuple containing only one element ("a",) # need to add a comma

Advantages: tuple is faster than list; 'write protection' for data that does not need to be modified can make the code more secure

tuple与list可以相互转换,使用内置的函数list()和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 usage of tuples is in print statements, as in the following example:

name = "Runsen"
age = 20
print( "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, or an exception if there is noneValueError

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

6.3 Dictionaries

A dictionary consists of key-value pairs, and keys must be unique;

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

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

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

Use del d[key] to delete key-value pairs; to judge 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) # True
print(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, use the elements in the sequence seq as the keys of the dictionary, and val is the initial value corresponding to all the keys of the dictionary (the 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 value corresponding to the key key in the dictionary dict, if the key does not exist in the dictionary, returns the value of default (the default value is None)

d5 = {
    
    1:"one", 2:"two", 3:"three"}
print (d5.get(1) )#one
print (d5.get(5)) #None
print (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) ) #True
print (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 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 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 will be raised

d9 = {
    
    1:"one", 2:"two", 3:"three"}
print (d9.pop(1) )#one
print( d9) #{2: 'two', 3: 'three'}
print( d9.pop(5, None)) #None
try:
    d9.pop(5)  # raise KeyError
except KeyError, ke:
    print ( "KeyError:", ke) #KeyError:5
  • drink()

Delete any key-value pair and return the key-value pair, if the dictionary is empty, an exception KeyError will be raised

d10 = {
    
    1:"one", 2:"two", 3:"three"}

print (d10.popitem() ) #(1, 'one')
print (d10)  #{2: 'two', 3: 'three'}
  • setdefault(key,[default])

If there is a key in the dictionary, return the vlaue value, if there is no key, add the key, the value is default, the default is None

d = {
    
    1:"one", 2:"two", 3:"three"}

print (d.setdefault(1))  #one
print (d.setdefault(5))  #None
print( d)  #{1: 'one', 2: 'two', 3: 'three', 5: None}
print (d.setdefault(6, "six")) #six
print (d)  #{1: 'one', 2: 'two', 3: 'three', 5: None, 6: 'six'}
  • update(dict2)

Add the elements of dict2 to the dict, and when the key is repeated, it will overwrite the key value in the 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 synchronously. 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()

Return 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

Sequence type means that the elements in the container are accessed in index order starting from 0, and one or more elements can be accessed at a time; lists, tuples, and strings are all sequences.
The three main characteristics of the sequence are

  • Indexing and Slicing Operators
  • index to get specific element
  • Slicing can get partial sequence

Indexing and Slicing Operators

numbers = ["zero", "one", "two", "three", "four"]
  
print (numbers[1] )# one
print (numbers[-1] )# four
#print( numbers[5]) # raise IndexError
print (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 (before the colon) in the slice operator indicates where the slice begins, and the second number (after the colon) indicates where the slice ends.

If you don't specify the first number, Python starts at the beginning of the sequence. If no second number is specified, Python stops at the end of the sequence.

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

At last

Baozi, who just started to get in touch with Python, you can private message me if you don’t understand anything

I've also prepared tons of free video tutorials, PDF e-books, and source code! Just pick up the business card at the end of the article!

Guess you like

Origin blog.csdn.net/yxczsz/article/details/128636733