程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] advanced variable customs clearance Tutorial Part I (list, tuple, dictionary)

編輯:Python

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 luck

This article is from the column :Python Basic course
Welcome to the support subscription column ️

Write it at the front

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 of articles

  • Write it at the front
  • 1 list
    • 1.1 List description
    • 1.2 Common operations of list
      • 1.2.1 Search and modify the value of the list
      • 1.2.2 Add data to the list
      • 1.2.3 Delete data from the list
      • 1.2.4 Statistical methods in the list
      • 1.2.5 Sorting and inversion of lists
    • 1.3 Iterated list
  • 2 Tuples
    • 2.1 Tuple description
    • 2.2 Common operations of tuples
    • 2.3 Iterative traversal of tuples
    • 2.4 Mutual transformation of tuples and lists
  • 3 Dictionaries
    • 3.1 The dictionary says
    • 3.2 Common operation of dictionaries
      • 3.2.1 Search, addition, deletion and modification of the dictionary
      • 3.2.2 Dictionary Statistics 、 Merge and empty
    • 3.3 Iterative traversal of the dictionary
    • 3.4 Dictionary and list integrated application scenarios
  • At the end


1 list

1.1 List description

  • List The list is Python The most frequently used data type in , In other languages it is usually an array ;
  • Lists are used to store a list of information , Use [ ] Definition , Use... Between data , Separate ;
  • Index of the list , It can also be called a subscript , It's from 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 :

1.2 Common operations of list

1.2.1 Search and modify the value 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 ']

1.2.2 Add data to the list

If you want to Add data to the list , It is mainly realized through the following three methods :

Method name explain append(self,object) Append data to the end of the list insert(self,index,object) Inserts data at the specified index position in the list extend(self,iterable) Splice a list to the end of the list

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 :

1.2.3 Delete data from the list

If you want to Delete data from the list , It is mainly realized through the following three methods :

Method name explain remove(self,object) Delete the specified data in the list ( If it appears more than once, delete the first , If not, report an error )pop(self,index) When parameters are not used index when , By default, delete and return the data at the end of the list ; Using parameter index You can specify the index that you want to delete data clear(self) clear list

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

1.2.4 Statistical methods in the list

The commonly used list statistics methods are shown in the following table :

Method name explain len(list) Count the number of elements in the list count(object) Count the number of times a certain data appears in the list

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 :

1.2.5 Sorting and inversion of lists

The relevant methods are shown in the table below :

Method name explain sort() Ascending sort sort(reverse = True) null reverse() Reverse list

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 :

1.3 Iterated list

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)


2 Tuples

2.1 Tuple description

  • Tuple Tuples are similar to lists , The biggest difference is the tuple Element cannot be modified
  • Tuples represent a sequence of elements , Used to store a string of information , Use... Between data , Separate ;
  • Tuples use ( ) 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 ,

2.2 Common operations of tuples

Because the elements in tuples are immutable , therefore python Tuple methods provided are usually read-only , Commonly used index() and count()

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

2.3 Iterative traversal of tuples

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

2.4 Mutual transformation of tuples and lists

  • Tuples are converted to lists , adopt list Function implementation
  • Convert list to tuple , adopt 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 :


3 Dictionaries

3.1 The dictionary says

  • Dictionary use {} Definition , yes An unordered collection of objects ;
  • Dictionary use Key value pair Store the data , using , Separate ;
  • key key It's the index , value value Is the data ;
  • Use between key values : Separate ;
  • The key must be unique , And must be a string 、 A number or tuple , Values can be of any data type .

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 :

3.2 Common operation of dictionaries

3.2.1 Search, addition, deletion and modification of the dictionary

️ 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)

3.2.2 Dictionary Statistics 、 Merge and empty

List of methods involved :

Method name explain len(dict) Count the number of dictionary key value pairs update(temp_dict) take update_dict The dictionary is merged with the original dictionary , If the merged dictionary contains key value pairs that already exist , Will overwrite the original key value pair clear() Clear all elements in the dictionary

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 :

3.3 Iterative traversal of the dictionary

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]))

3.4 Dictionary and list integrated application scenarios

  • Use Multiple key value pairs , Describe information about an item ;
  • take Multiple dictionaries in one list , Do the same processing for each dictionary inside the loop body

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)


At the end

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 .”


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved