search
HomeBackend DevelopmentPython TutorialThe second Python knowledge point compiled for beginners

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. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft