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

Python queues (lists, tuples, dictionaries, collections)

編輯:Python

List of articles

  • One 、 list
      • 1. What is a list
      • 2. Access the values in the list
      • 3. Assignment of the list
        • 3.1 Add an element to the list
        • 3.2 Find elements in the list
        • 3.3 Modify elements in the list
        • 3.4 Delete the element from the list
      • 4. Loop traversal of list
        • 4.1 random random number
        • 4.2 Loop traversal of list
      • 5. Sorting operation of list
        • 5.1 Ascending and descending sort
        • 5.2 Bubble sort
        • 5.3 Selection sort
        • 5.4 Insertion sort
      • 6. Nesting of lists
  • Two 、 Tuples
      • 1. What is a tuple
      • 2. The basic operation of tuples
      • 3. Built in functions for tuples
      • 4. Loop traversal of tuples
  • 3、 ... and 、 Dictionaries
      • 1. What is a dictionary
      • 2. Basic operation of dictionary
        • 2.1 According to the key access value
        • 2.2 Add and modify dictionary elements
        • 2.3 Delete dictionary elements
        • 2.4 Get key view of dictionary
        • 2.5 Get the value view of the dictionary
        • 2.6 Get the element view of the dictionary
      • 3. Traversal of dictionaries
        • 3.1 Traverse the key of the dictionary
        • 3.2 Traversal dictionary value
        • 3.3 Traversing the elements of the dictionary
        • 3.4 Traverse the key value pairs of the dictionary

One 、 list

1. What is a list

  • Sequence is Python The most basic data structure in . Each value in the sequence has a corresponding position value , Call it an index , The first index is 0, The second index is 1, And so on ;

  • Lists are the most commonly used Python data type , It can appear as a comma separated value in square brackets ;

  • The data items of a list do not need to have the same type , Create a list , Just enclose the different data items separated by commas in square brackets .

As shown below :

list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']

2. Access the values in the list

list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[0] )
print( list[1] )
print( list[2] )
# Output results 
red
green
blue

Indexes can also start at the end , The index of the last element is -1, The next one is -2, And so on .

Example

list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[-1] )
print( list[-2] )
print( list[-3] )
# Output results 
black
white
yellow

Use the subscript index to access the values in the list , You can also use square brackets [] Intercepting characters in the form of , As shown below :

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[0:4])
# Output results 
[10, 20, 30, 40]
  • Use negative index values to intercept , as follows
list = ['Google', 'Runoob', "Zhihu", "Taobao", "Wiki"]
print ("list[1]: ", list[1]) # Read second bit 
print ("list[1:-2]: ", list[1:-2]) # From the second place ( contain ) Intercept to the penultimate ( It doesn't contain )
# Output results 
list[1]: Runoob
list[1:-2]: ['Runoob', 'Zhihu']

3. Assignment of the list

# Example 
lst=[1,2,3,4,5,6]
lst.append(10) # Append at the end of the list 10
lst.append(8) # Append at the end of the list 8
lst[0:2]=7,9 # Put the subscript 0 and 2 Value 1,2 Replace with 7,9
print(lst)
# Output results 
[7, 9, 3, 4, 5, 6, 10, 8]
------------------------------------------------------------------------------------------------
list.append( Elements ) # Append an element to the end of the list 
list[index]= Elements # Change the value of the corresponding subscript to the element 
list[index]= Elements 1, Elements 2 # By default, the tuple is inserted into this location 
list[index1,index2]= Elements 1, Elements 2 # Will insert... Bit by bit 
list[index1,index2]= Elements 1, Elements 2, Elements 3... # Will replace the insert 
list[index1,index2]= Elements 1 # Cannot insert when the value is less than the position , Will report a mistake 

3.1 Add an element to the list

  • There are many ways to add elements to the list , As follows :
    ① adopt append You can add elements... To the list .
    ② adopt extend You can add elements from another list to the list
    ③ adopt insert You can insert elements before the specified position .

PS: insert Consume more resources , Avoid using

Example

lst=[1,2,3,4,5]
lst2=[50,90,80]
lst.extend(lst2) # stay lst Back up lst2 Value 
print(lst)
# Output results 
[1, 2, 3, 4, 5, 50, 90, 80]
#add and extend The difference is that ,extend Is to add values directly to lst In the middle , and add The appended result will be returned , And the original value is constant 
lst=[1,2,3,4,5]
lst2=[50,90,80]
a=lst.__add__(lst2) # use a To receive the value it returns 
print(lst.__add__(lst2))
print(a)
# Output results 
[1, 2, 3, 4, 5, 50, 90, 80]
[1, 2, 3, 4, 5, 50, 90, 80]
lst=[1,2,3,4,5]
lst.append(10)
lst.append(8)
print(lst)
lst.insert(0,66) # The subscript for 0 Insert at 66
print(lst)
# Output results 
[1, 2, 3, 4, 5, 10, 8]
[66, 1, 2, 3, 4, 5, 10, 8]

3.2 Find elements in the list

The operators for finding elements in the list include :

  • in If it exists, the result is True, Otherwise False
  • not in If not, the result is True, Otherwise False
lst=[1,2,3,4,5]
print(5 in lst)
print(6 in lst)
print(5 not in lst)
print(6 not in lst)
print(lst.index(4)) #index You can also find elements , And you can find out where it is 
# Output results 
True
False
False
True
3

3.3 Modify elements in the list

The modification of list elements is also realized through subscripts

Example

lst=[1,2,3,4,5]
lst[1],lst[3]=22,66
lst[0:5]=55,66 # Multiple elements replace values at multiple locations 
print(lst)
# Output results 
[1, 22, 3, 66, 5]
[55, 66]

3.4 Delete the element from the list

There are three common ways to delete list elements , As follows :

  • del : Delete according to subscript
lst=[1,2,3,4,5]
del lst[0]
print(lst)
del lst[0:3] # Batch deletion 
print(lst)
# Output results 
[2, 3, 4, 5]
[5]
  • pop : Delete the last element
lst=[1,2,3,4,5]
lst.pop() # You can also specify subscript deletion 
print(lst)
# Output results 
[1, 2, 3, 4]
  • remove : Delete... According to the value of the element
lst=[1,2,3,4,5]
lst.remove(3) # Delete according to the specified value 
print(lst)
# Output results 
[1, 2, 4, 5]

4. Loop traversal of list

4.1 random random number

random() Method returns a randomly generated real number , It's in [0,1) Within the scope of .

random() The grammar of :
import random
random.random()

Example

import random
lst=[]
for i in range(5):
lst.append(random.randint(0,100))
print(lst)
# Output results 
[0, 39, 99, 70, 30]

4.2 Loop traversal of list

When the range of random numbers is too large , Not easy to find and use , In this case, you need to use traversal

Use for Loop through the list

# Generate random lists 
lst=[]
for i in range(5):
lst.append(random.randint(0,100))
print(lst)
# Traversal of list 
for x in lst:
print(x)
# Output results 
[50, 54, 36, 23, 87]
50
54
36
23
87
---------------------------------------------------------------------------------------------
# Use length traversal 
for x in range(lst.__len__()): #lst.__len__() representative lst The length of , by 5, That's subscript 0 To 4 Value 
print(lst[x])
# Output results 
[50, 54, 36, 23, 87]
50
54
36
23
87

Use while Loop through the list

names_list=['xiaowang','xiaozhang','xiaohua']
length=len(names_list)
i=0
while i < length:
print(names_list)
i+=1
# Output results 
['xiaowang', 'xiaozhang', 'xiaohua']
['xiaowang', 'xiaozhang', 'xiaohua']
['xiaowang', 'xiaozhang', 'xiaohua']

In addition to traversal, we can also use it to batch change the values in the list

for x in range(lst.__len__()):
lst[x]+=1
for x in lst:
print(x)
# Output results 
[26, 81, 54, 22, 2]
27
82
55
23
3

The difference between the two ways

lst=[]
for i in range(5):
lst.append(random.randint(0,100))
print(lst)
------------------------------------------------------------------------------------------------
#type1:
for x in lst: #x It's a temporary variable , It's just lst Copy of each element in 
print(x) # The operation of copying cannot affect the element itself 
# But if you pass in an address , Changes to its content will be passed on to the outside 
#type2:
for x in range(lst.__len__()):
print(lst[x]) #lst[x] The operation is lst The element itself 
# Output results # You can see the returned result , No change in value 
[17, 77, 67, 85, 40]
17
77
67
85
40

5. Sorting operation of list

5.1 Ascending and descending sort

The sorting of lists can be realized in the following two ways :
① sort Method : The elements of the list are arranged in a specific order
② reverse Method : Invert the list

sort() Function to sort the original list , If you specify parameters , Then use the comparison function specified by the comparison function .
grammar

list.sort(cmp=None, key=None, reverse=False)
# Parameters 
cmp -- Optional parameters , If this parameter is specified, the method of this parameter will be used for sorting .
key -- It's basically a comparison element , There is only one parameter , The parameters of the specific function are taken from the iterable object , Specifies an element in an iterable object to sort .
reverse -- Sort rule ,reverse = True Descending , reverse = False Ascending ( Default ).

Example

# Method 1 :
lst=[24, 37, 91, 95, 71]
lst.sort(reverse=True) # null 
print(lst)
# Output results 
[95, 91, 71, 37, 24]
-------------------------------------------------------------------------------------------------
# Method 2 :
lst=[24, 37, 91, 95, 71]
lst.sort()
lst.reverse()
print(lst)
# Output results 
[95, 91, 71, 37, 24]

5.2 Bubble sort

Double cycle
External circulation control compares the number of rounds
The inner loop controls the number of comparisons per round

lst= [15, 24, 6, 52, 88]
for x in range(len(lst)-1): # There is only one element left in the last round , There is no need to compare , therefore -1
for y in range(len(lst)-x-1):
# A maximum value can be determined for each round , So each round is reduced by one comparison 
if lst[y]>lst[y+1]:
tmp=lst[y]
lst[y]=lst[y+1]
lst[y+1]=tmp
print(lst)
# Output results 
[6, 15, 24, 52, 88]

5.3 Selection sort

Selection sort : Each time you traverse from front to back , Find a minimum value , Swap with this location

import random
lst=[]
for x in range(10):
lst.append(random.randint(0,100))
print(lst)
for x in range(len(lst)-1): # The last position doesn't need to be compared 
tmp=lst[x] # Set an initial value for each round , The purpose is to compare with the following values 
idx=x
for y in range(x+1,len(lst)): # Traverse backwards from the initial value 
if(tmp>lst[y]): # To find the minimum in a round 
tmp=lst[y] # The minimum value is stored in the tmp in 
idx=y # Subscripts are saved in idx in 
else:
lst[idx]=lst[x] # Subscript according to the minimum value , Put the initial value in 
lst[x]=tmp # Put the minimum value in the initial position 
print(lst)
# Output results 
[60, 34, 83, 72, 96, 66, 3, 25, 57, 13]
[3, 13, 25, 34, 57, 60, 66, 72, 83, 96]

5.4 Insertion sort

Insert a sort logic example

# Insert values into an ordered array and keep the order 
arr=[10,20,30,50,80]
a=int(input(" Please enter an integer "))
arr.append(a)
idx=len(arr)-1
while idx>0:
# Traverse from back to front 
idx-=1
# Meet someone smaller than yourself , Insert after 
if a>arr[idx]:
arr[idx+1]=a
break
# Meet someone older than yourself , Large values move backward 
else:
arr[idx+1]=arr[idx]
# If you don't insert it in the end , Insert in the first place 
if idx==0:
arr[0]=a
print(arr)
# Output results 
Please enter an integer 5
[5, 10, 20, 30, 50, 80]
Please enter an integer 888
[10, 20, 30, 50, 80, 888]
  • Insert sort example

Just started an element , That is, order , One element at a time , Form a new sequence , Apply logic for inserting elements , Keep it in order

import random
lst=[]
for x in range(10):
lst.append(random.randint(0,100))
print(lst)
for x in range(1,len(lst)):
idx=x
tmp=lst[x]
while x>0:
x-=1
if tmp>=lst[x]:
lst[x+1]=tmp
break
else:
lst[x+1]=lst[x]
if x==0:
lst[0]=tmp
print(lst)
# Output results 
[46, 38, 42, 57, 40, 37, 59, 57, 75, 35]
[35, 37, 38, 40, 42, 46, 57, 57, 59, 75]

6. Nesting of lists

The nesting of lists refers to the elements of a list and a list

Example

school_names = [[' Peking University, ',' Tsinghua University '],[' Nankai University ',' Tianjin University ',' Tianjin Normal University '],[' Shandong University ',' Ocean University of China ']]
# Traversal of nested lists 
for x in school_names:
for y in range(len(x)):
print(x[y])
or
for x in range(len(school_names)):
for y in range(len(school_names[x])):
print(school_names[x][y])
or
for x in school_names:
for y in x:
print(y)
# Output results 
Peking University,
Tsinghua University
Nankai University
Tianjin University
Tianjin Normal University
Shandong University
Ocean University of China

Two 、 Tuples

1. What is a tuple

Python A tuple of is similar to a list , The difference is that the elements of a tuple cannot be modified .
Tuples wrap elements in parentheses , The list wraps the elements in square brackets .

2. The basic operation of tuples

Example

tpl=(1,2,3,4,5,6)
print(tpl[0])
print(tpl[0:3])
print(tpl[0:5:2])
# Output results 
1
(1, 2, 3)
(1, 3, 5)
tpl=(1,2,3,4,5,6)
tpl[0]=5
print(tpl)
# We found an error in the output result , Because elements in tuples cannot be modified 

Change tuples to lists

tpl=(1,2,3,4,5)
print(list(tpl))
# Output results 
[1, 2, 3, 4, 5]

3. Built in functions for tuples

Method describe len(tuple) Count tuple elements max(tuple) Returns the maximum value of an element in a tuple min(tuple) Returns the minimum value of an element in a tuple tuple(seq) Convert list to tuple

Example

tpl=(1,2,3,4,5)
print(len(tpl))
print(max(tpl))
print(min(tpl))
# Output results 
5
5
1

4. Loop traversal of tuples

tpl=(1,2,3,4,5)
for x in tpl:
print(x)
# Output results 
1
2
3
4
5

3、 ... and 、 Dictionaries

1. What is a dictionary

A dictionary is a container for storing data , It is similar to a list , Can store multiple data .

Example

info = {
'name':' Monitor of the class ','sex':'f','address':' Beijing '}
Each element of the dictionary consists of keys and values , for example , above ’name’ As the key ,‘ Monitor on duty ’

Be careful :

  • dict As Python Keywords and built-in functions , Variable names are not recommended to be named dict;
  • Keys are usually the only , If you repeat the last key value pair, the previous one will be replaced , Value doesn't need to be unique .

2. Basic operation of dictionary

2.1 According to the key access value

Example

info={
'name':' Monitor of the class ','sex':'f','address':' Beijing '}
print(info['sex'])
print(info['address'])
# Output results 
f
Beijing

When we want to get the value corresponding to a key but are not sure whether the key exists , have access to get Method to get

d={
"name":" rhubarb ","age":5,"strain":" Labrador "} #json character string 
print(d.get("birthday"))
print(d.get("name"))
# Output results 
None
rhubarb

2.2 Add and modify dictionary elements

Example

d={
"name":" rhubarb ","age":5,"strain":" Labrador "}
d["name"]=" Trump " # Modifying elements 
d["birthday"]="2021-1-17" # Additive elements 
print(d)
# Output results 
{
'name': ' Trump ', 'age': 5, 'strain': ' Labrador ', 'birthday': '2021-1-17'}
d={
"name":" rhubarb ","age":5,"strain":" Labrador "}
print(d)
d.setdefault("abc","sorry") # If key Already exist , Then do nothing , If key non-existent , Insert... With the default value 
print(d)
# Output results 
{
'name': ' rhubarb ', 'age': 5, 'strain': ' Labrador '}
{
'name': ' rhubarb ', 'age': 5, 'strain': ' Labrador ', 'abc': 'sorry'}

2.3 Delete dictionary elements

del: Delete Dictionary . The dictionary is deleted directly from memory , You can no longer access values by key .
clear: Empty dictionary elements . The dictionary is still in memory , But there are no elements .
d={
"name":" rhubarb ","age":5,"strain":" Labrador "}
del d["strain"] # Delete "strain" Key and value 
print(d)
d.clear() # Empty dictionary elements 
print(d)
# Output results 
{
'name': ' rhubarb ', 'age': 5, 'strain': ' Labrador '}
{
'name': ' rhubarb ', 'age': 5}
{
}

2.4 Get key view of dictionary

keys() Method to get the key view of the dictionary , To reflect the changes of keys in the dictionary in real time
Example
dct={
"name":"zhangsan","age":18,"gender":"male","id":10}
keys=dct.keys()
print(keys)
dct.setdefault("birthday","2022-01") # Add a key value 
print(keys)
# Output results 
dict_keys(['name', 'age', 'gender', 'id'])
dict_keys(['name', 'age', 'gender', 'id', 'birthday'])

Traverse the key of the dictionary

dct={
"name":"zhangsan","age":18,"gender":"male","id":10}
dct.setdefault("birthday","2022-01")
for k in keys:
print(k+":",dct[k])
# Output results 
name: zhangsan
age: 18
gender: male
id: 10
birthday: 2022-01

2.5 Get the value view of the dictionary

values() Method to get the value view of the dictionary , To reflect the change of the value in the dictionary in real time .
dct={
"name":"zhangsan","age":18,"gender":"male","id":10}
dct.setdefault("birthday","2022-01")
values=dct.values()
print(values)
# In the form of a list , Only values without keys 
# Output results 
dict_values(['zhangsan', 18, 'male', 10, '2022-01'])

Dynamic real-time display of change results

dct={
"name":"zhangsan","age":18,"gender":"male","id":10}
keys=dct.keys()
dct.setdefault("birthday","2022-01")
values=dct.values()
dct.setdefault("now","2022-01")
print(values)
# Output results 
dict_values(['zhangsan', 18, 'male', 10, '2022-01', '2022-01'])

2.6 Get the element view of the dictionary

items() Method to get the element view of the dictionary , To reflect the changes of key value pairs in the dictionary in real time .

Example

dct={
"name":"zhangsan","age":18,"gender":"male","id":10}
keys=dct.keys()
dct.setdefault("birthday","2022-01")
itms=dct.items()
print(itms)
# Output results 
dict_items([('name', 'zhangsan'), ('age', 18), ('gender', 'male'), ('id', 10), ('birthday', '2022-01')])

Traverse the key value pairs of the dictionary

dct={
"name":"zhangsan","age":18,"gender":"male","id":10}
keys=dct.keys()
dct.setdefault("birthday","2022-01")
itms=dct.items()
print(itms)
for x,y in itms:
print(x+":",y)
# Output results 
dict_items([('name', 'zhangsan'), ('age', 18), ('gender', 'male'), ('id', 10), ('birthday', '2022-01')])
name: zhangsan
age: 18
gender: male
id: 10
birthday: 2022-01

3. Traversal of dictionaries

3.1 Traverse the key of the dictionary

dict_demo={
'Name':'Lisi','Age':18}
for key in dict_demo.keys():
print(keys)
# Output results 
dict_keys(['name', 'age', 'gender', 'id', 'birthday'])
dict_keys(['name', 'age', 'gender', 'id', 'birthday'])

3.2 Traversal dictionary value

dict_demo={
'Name':'Lisi','Age':18}
for value in dict_demo.values():
print(value)
# Output results 
Lisi
18

3.3 Traversing the elements of the dictionary

dict_demo={
'Name':'Lisi','Age':18}
for item in dict_demo.items():
print(item)
# Output results 
('Name', 'Lisi')
('Age', 18)

3.4 Traverse the key value pairs of the dictionary

dict_demo={
'Name':'Lisi','Age':18}
for key,value in dict_demo.items():
print("key=%s,value=%s"%(key,value))
# Output results 
key=Name,value=Lisi
key=Age,value=18

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