The second Python knowledge point compiled for beginners
python video tutorial column introduces the second Python basics.
#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'}复制代码
- #setdefault(key,[default])
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)
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()
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()
d = {1:"one", 2:"two", 3:"three"}for key in d.viewkeys(): print( key)#1#2#3复制代码
- viewvalues()
d = {1:"one", 2:"two", 3:"three"}for value in d.viewvalues(): print (value)#one#two#three复制代码
- 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'] 复制代码
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

Using python in Linux terminal...

Fastapi ...
