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
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.