Personal home page : Huang Xiaohuang's blog home page
️ Stand by me : give the thumbs-up Collection Focus on
Maxim : Only one step at a time can we accept the so-called luckThis article is from the column :Python Basic course
Welcome to the support subscription column ️
This paper deals with Python Advanced variables in : list 、 Tuples 、 The dictionary summarizes and explains the knowledge . There are many strings in advanced variables , Bloggers will put it in the next chapter :
【Python】 Advanced variable clearance Tutorial Part II ( String theme )
Explain to you , Interested students can subscribe to the column , Or pay attention to me , Don't miss the first update . All right. , This is the end of the gossip , Start learning about advanced variables ~~~
List
The list is Python
The most frequently used data type in , In other languages it is usually an array ;[ ]
Definition , Use... Between data ,
Separate ;0
At the beginning Let's briefly define a list , Store the names of three students , The code is as follows :
students_name = [" Huang Xiaohuang ", " Your beans ", " My wife is good at leisure "]
By way of illustration , Learn more about the storage structure of the list :
List Find value You just need to index to find , The following code , See note for results :
students_name = [" Huang Xiaohuang ", " Your beans ", " My wife is good at leisure "]
students_name[0] # Huang Xiaohuang
students_name[1] # Your beans
students_name[2] # My wife is good at leisure
It should be noted that , The list value cannot exceed the maximum value of the index , That is, the length of the list - 1, Otherwise, an error will be reported
if necessary Find the index of the list , Through index()
Method realization :
students_name = [" Huang Xiaohuang ", " Your beans ", " My wife is good at leisure "]
students_name.index(" Huang Xiaohuang ") # 0
students_name.index(" Your beans ") # 1
students_name.index(" My wife is good at leisure ") # 2
Of course , If the data passed is not in the list , The program will report an error
Modify list data You only need to modify it directly through the index :
students_name = [" Huang Xiaohuang ", " Your beans ", " My wife is good at leisure "]
# Modifying data
students_name[1] = " Big head "
print(students_name) # [' Huang Xiaohuang ', ' Big head ', ' My wife is good at leisure ']
If you want to Add data to the list , It is mainly realized through the following three methods :
The code example is as follows :
students_name = [] # First define an empty list
# Add three pieces of data
students_name.append(" Huang Xiaohuang ")
students_name.append(" Ma Xiaomiao ")
students_name.append(" Big head ")
print(students_name) # [' Huang Xiaohuang ', ' Ma Xiaomiao ', ' Big head ']
# insert data
students_name.insert(2, " Little ox and horse ")
print(students_name) # [' Huang Xiaohuang ', ' Ma Xiaomiao ', ' Little ox and horse ', ' Big head ']
# Splicing list
my_list = [" Xiao peng ", " The geometric heart is cool "]
students_name.extend(my_list)
print(students_name) # [' Huang Xiaohuang ', ' Ma Xiaomiao ', ' Little ox and horse ', ' Big head ', ' Xiao peng ', ' The geometric heart is cool ']
result :
If you want to Delete data from the list , It is mainly realized through the following three methods :
The code example is as follows :
mylist = [" Huang Xiaohuang ", " Your beans ", " Whirlpool Naruto ", " A straw hat flies on the road "]
# Delete specified data
mylist.remove(" Huang Xiaohuang ")
print(mylist) # [' Your beans ', ' Whirlpool Naruto ', ' A straw hat flies on the road ']
# Delete end data
mylist.pop()
print(mylist) # [' Your beans ', ' Whirlpool Naruto ']
# Empty
mylist.clear()
print(mylist) # []
result :
meanwhile , Deleting data can also be done through del Keyword implementation , But pay attention to the difference : Use del Is to delete variables from memory , This variable cannot be used in subsequent code
mylist = [" Huang Xiaohuang ", " Your beans ", " Whirlpool Naruto ", " A straw hat flies on the road "]
del mylist[1]
print(mylist) # [' Huang Xiaohuang ', ' Whirlpool Naruto ', ' A straw hat flies on the road ']
del mylist
print(mylist) # NameError: name 'mylist' is not defined
The commonly used list statistics methods are shown in the following table :
Refer to the code example :
mylist = [" Huang Xiaohuang ", " Your beans ", " Whirlpool Naruto ", " A straw hat flies on the road ", " Huang Xiaohuang "]
mylist_len = len(mylist)
print(" The length of the list ( Element number ): %d" % mylist_len) # 5
count = mylist.count(" Huang Xiaohuang ")
print(" Huang Xiaohuang Number of occurrences : %d" % count) # 2
result :
The relevant methods are shown in the table below :
It should be noted that , Ascending sort is from small to large for numbers ; For strings and characters , Is the dictionary order , such as a Than z Small
Reference sample code :
words = ["abc", "Abc", "z", "dbff"]
nums = [9, 8, 4, 2, 2, 3]
# Ascending sort
words.sort()
nums.sort()
print(words) # ['Abc', 'abc', 'dbff', 'z']
print(nums) # [2, 2, 3, 4, 8, 9]
# null
words.sort(reverse=True)
nums.sort(reverse=True)
print(words) # ['z', 'dbff', 'abc', 'Abc']
print(nums) # [9, 8, 4, 3, 2, 2]
# reverse
nums.reverse()
print(nums) # [2, 2, 3, 4, 8, 9]
result :
Traversal refers to getting data from a list from beginning to end , Use for
Loops are easy to implement , The basic syntax format is as follows :
# for Variables used inside the loop in list
for name in name_list:
# The operation on the list inside the loop
print(name) # Like printing
Sample code and results :
student_list = [" Huang Xiaohuang ", " Ma Xiaomiao ", " Big head ", " Little ox and horse "]
# Iterate through
for student in student_list:
print(student)
Tuple
Tuples are similar to lists , The biggest difference is the tuple Element cannot be modified ,
Separate ;( )
Definition , Index from 0
Start .Example 1️⃣ Create an empty tuple
tuple = ()
Example 2️⃣ Create a tuple
tuple = (" Huang Xiaohuang ", " Monkey D Luffy ", " Nami ")
When a tuple contains only one element , You need to add... After the element ,
Because the elements in tuples are immutable , therefore python Tuple methods provided are usually read-only , Commonly used
index()
andcount()
Sample code and results :
my_tuple = (" Huang Xiaohuang ", " Ma Xiaomiao ", " A straw hat flies on the road ", " Huang Xiaohuang ")
# Read index
print(my_tuple.index(" Ma Xiaomiao ")) # 1
# Count the number of times
print(my_tuple.count(" Huang Xiaohuang ")) # 2
It is similar to the traversal of a list , But in actual development , We don't often go through the epoch group , Unless you can confirm Data types of elements in tuples .
# for Variables used inside the loop in Tuples
for name in name_touple:
# Operations on tuples inside a loop
print(name) # Like printing
Summary : stay Python Can be used in for Loop through all non numeric variables : list 、 Tuples 、 Strings and dictionaries
list
Function implementation tuple
Function implementation Reference code :
temp_tuple = (" Huang Xiaohuang ", " Ma Xiaomiao ", " A straw hat flies on the road ")
my_list = list(temp_tuple)
print(my_list)
print(type(my_list))
my_tuple = tuple(my_list)
print(my_tuple)
print(type(my_tuple))
result :
{}
Definition , yes An unordered collection of objects ;,
Separate ;key
It's the index , value value
Is the data ;:
Separate ;Let's briefly define a dictionary , The code is as follows :
nezuko = {
"name": " Your beans ",
"age": 6,
"height": 145,
"phone": 123456789}
By way of illustration , Understand the storage structure of the dictionary in detail :
️ Through the study of lists and tuples , I must have known that the index values have been added and deleted , Here is a code example :
1. Find value
Dictionary values are also indexed , It's just , The index of the dictionary is key. It should be noted that , When the value is fetched , If specified key non-existent , The program will report an error !
nezuko = {
"name": " Your beans ",
"age": 6,
"height": 145,
"phone": 123456789}
# Find value , Value
print(nezuko["name"])
print(nezuko["age"])
print(nezuko["height"])
print(nezuko["phone"])
2. Add and modify values
stay python Adding and modifying values in is simple , Just use the index to add or modify . If key There is , Data will be modified ; If key non-existent , Key value pairs will be added .
nezuko = {
"name": " Your beans ",
"age": 6,
"height": 145,
"phone": 123456789}
# add to
nezuko[" Gender "] = " Woman "
# modify
nezuko["age"] = 3
# Print
print(nezuko)
3. Delete values and dictionaries
There are two ways to delete , Use pop() Method specification key Delete or use keywords del And designate key Delete . Of course , It can also be done through del Keyword delete Dictionary .
nezuko = {
"name": " Your beans ",
"age": 6,
"height": 145,
"phone": 123456789}
# Delete
del nezuko["phone"]
nezuko.pop("height")
print(nezuko)
# Delete Dictionary
del nezuko
print(nezuko)
List of methods involved :
Sample code :
nezuko = {
"name": " Your beans ",
"age": 6,
"height": 145,
"phone": 123456789}
# Count the number of key value pairs
nezuko_count = len(nezuko)
print(" Dictionaries nezuko The number of key value pairs is : %d" % nezuko_count)
# Merge two dictionaries
nezuko_new = {
" Gender ": " Woman ",
" hobby ": " Biting bamboo tube ",
"age": 10}
nezuko.update(nezuko_new)
print(" After the merger " + str(nezuko))
# Empty list elements
nezuko.clear()
print(" After emptying : " + str(nezuko))
result :
In actual development , The dictionary traversal requirements are not many , Because we can't determine the data type of each key value pair in the dictionary .
Traversal syntax :
# for Used internally key Variable in Dictionary name
for k in dict:
# Specific operation
print("%s: %s" % (k, dict[k]))
Sample code and results :
commodities = {
" Name of commodity ": " The shampoo ",
" Price ": "$8.99"}
# Traverse
for k in commodities:
print("%s \t: %s" % (k, commodities[k]))
Sample code and results :
Try to store item information as a dictionary , And store all items in the list for traversal and modification
commodities_list = [
{
" Name of commodity ": " The shampoo ", " Price ": "$8.99"},
{
" Name of commodity ": " The headset ", " Price ": "$78.99"},
{
" Name of commodity ": " Solid state disk ", " Price ": "$99.99"},
]
# Traverse Increase the price of all commodities 100 And print
for commodity in commodities_list:
# It's used here lstrip First character deletion of string The back can speak Ignore first
commodity[" Price "] = "$" + str(float(commodity[" Price "].lstrip("$")) + 100)
print(commodity)
The above is the whole content of this article , The follow-up will continue Free update , If the article helps you , Please use your hands Point a praise + Focus on , Thank you very much ️ ️ ️ !
If there are questions , Welcome to the private letter or comment area !
Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”