Python Learning path 04--list and dictionary

Source: Internet
Author: User

Lists and dictionaries

mutable data types in Python are: List and dictionary immutable types: numbers, strings, tuples speak lists and dictionaries today

A. List

1. Concept:
Variables: Use variables to store data, but variable store data can only store one data at a time
Question: What do I do if I want to store multiple data at once?
#需求: Store 5 People's age, ask for an average of age
Age1 = 10
Age2 = 15
Age3 = 30
Age4 = 17
Age5 = 24
Avg = (age1 + age2 + age3 + age4 + age5)/5
Workaround: Take the list
Function: Equivalent to a container that can store multiple data at the same time
Essence: A list is an ordered set of
Description: Ordered refers to the order in which the stored order of storage is the same as the order in which it is stored in memory.
2. Create a list: num = 10
Syntax: variable name = List
? List name = [Data 1, Data 2 ..... ]
Description
? A. Defining a list by []
? B. The data stored in the list is called an element
? C. The elements in the list are numbered from beginning to end, numbering starting from 0, which is called index, corner or subscript
? D. Index range: Number of elements in the 0~ list-1 "0~ The length of the list-1"
? E. Exceeding the index range: The index of the list is out of bounds
3. Access to elements in the list 3.1 Value
Code Demo:
#元素的访问
#1. Take a value
#语法: List name [index]
#索引: 0~4
List1 = [543,5,46,56,6]
NUM1 = list1[2]
Print (list1[2])
Print (NUM1)
#列表索引越界
#print (list1[-10]) #IndexError: List index out of range
#print (List1[5])
3.2. Replacement value
#语法: The element in the list name [index] = new Value list is essentially a variable, so the action to replace it is actually to reassign the variable "
LIST1[2] = 100
Print (list1[2])
4. Actions in the list
Code Demo:
#列表的操作
#1. List combination: +
List1 = [54,5,45,4]
List2 = ["abc", "Fhj", "GHFJG"]
#列表的组合并没有修改原来的列表, instead, a new list is generated
List3 = List1 + list2
Print (LIST3)
Print (List1)
Print (LIST2)
#2. Duplicate list elements: *
#2.1 You can store duplicate elements in a list
L1 = [20,20,40,45,54,20]
Print (L1)
#2.2
L2 = [10,20,30]
L3 = L2 * 3
Print (L3)
? #3. Determine whether an element is in the list: member operator [INT not in]
#注意: The result of a member operator operation is a Boolean value
#一般结合if语句使用
L4 = [34,54,56, "ANC"]
Print (in L4)
Print (in L4)
Print (in L4)
Print (L4)
"""
True
False
False
True
#4. Intercepting "slices" of the list
#4.1 intercept The specified interval: list name [start index: End index]
#特点: Related to the interval, Baotou does not pack tail front closed after the opening interval: [2,4)
L5 = [34,54,56, "ANC", 5,65,76,7677]
Print (L5[2:4])
#4.2 intercept from the beginning to the specified position
Print (L5[0:5])
Print (L5[:5])
#4.3 intercept from the specified position to the end
Print (L5[3:7])
Print (l5[3:])
#注意; If you want to take the last element, you can go beyond the scope of the index, in which case there will be no error
Print (l5[3:20])
5. Features of the list
Syntax: List name. function name ()
#1. Adding elements
#1.1 append (): Appending elements at the end of a list element
LIST11 = [10,20,30]
Print (LIST11)
#追加单个元素
List11.append (40)
Print (LIST11)
#追加多个元素
#list11. Append (50,60) #错误演示
#注意: Append multiple elements using the APPEND function, cannot be appended directly, append by the form of a list
List11.append ([50,60])
Print (LIST11)
#1.2 Extend (): extending, adding elements at the end of the list
list12 = [10,20,30]
Print (list12)
#追加单个元素
#list12. Extend (#错误演示): Extend cannot add a single element directly
# #iterable: The iterator of an iteration
#追加多个元素
#注意: Adding multiple elements using extend is still added as a list, but actually adding just the element "break add"
List12.extend ([50,60])
Print (list12)
Print ("~~~~~~~~")
#1.3 Insert (), insert, insert element at specified index
#格式: Insert (index, inserted data)
list13 = [10,20,30]
Print (LIST13)
List13.insert (2,40)
Print (LIST13)
#注意: Inserts one by one lists, inserts the entire list into the original list
List13.insert (1,[50,60])
Print (LIST13)
#2. Deleting elements
#2.1 Pop (index); Eject to remove the element at the specified index in the list
list21 = [10,20,30,40,50,60]
Print (list21)
#pop默认移除的是最后一个元素, the resulting result is the removed element
RESULT1 = List21.pop ()
Print (list21)
Print (RESULT1)
#移除指定位置的元素
List21.pop (2)
Print (list21)
#2.2 Remove (Element): Remove, Feature: Removes the element in the list "the first element in the list that can match from 0"
list22 = [10,20,30,40,50,60]
Print (list22)
List22.remove #等价于list22. Pop (0)
Print (list22)
#需求: Remove all the numbers in the list 10
list23 = [10,20,30,40,50,60,10,10,10,10,10,10]
"" "List23.remove (10)
Print (list23)
List23.remove (10)
Print (list23)
List23.remove (10)
Print (list23)
"""
num = 0
element = 10
Cou = List23.count (Element)
While Num < cou:
List23.remove (Element)
Print (list23)
num + = 1
Print (list23)
? #2.3 Clear (): Clear, clear all the elements in the list, the original list becomes empty list
List24 = [10,20,30,40,50,60,10,10,10,10,10,10]
List24.clear ()
Print (LIST24)
? #3. Get
#语法: Feature name (list name)
#3.1 len () length, gets the width of the list "gets the number of elements in the list"
LIST31 = [10,20,30,40,50,60,10,10,10,10,10,10]
length = Len (list31)
?
#3.2 Max (); Gets the maximum value of the element in the list min () min
Print (max (LIST31))
Print (min (list31))
?
#3.3 index (): index, the index value corresponding to the first element that is matched to from a list
INX1 = List31.index (10)
Print (INX1)
?
#3.4 count (), number to find the number of occurrences of the specified element in the list
c = List31.count (10)
Print (c)
?

#4. Other
#4.1 reverse () invert to reverse the output of the elements in the list
LIST41 = [10,20,30,40,50,60,10,10,10,10,10,10]
List41.reverse ()
Print (LIST41)
?
#4.2 sort () sorted by default ascending sort, note: internal operation in list
#升序
List41.sort ()
Print (LIST41)
#降序
List41.sort (Reverse=true)
Print (LIST41)
?
Sort #sorted () by default in ascending order, note: Generate a new list
List42 = [10,20,30,40,50,60,10,10,10,10,10,10]
#升序
NewList1 = sorted (list42)
Print (LIST42)
Print (NEWLIST1)
#降序
NewList2 = sorted (list42,reverse=true)
Print (NEWLIST2)
?
#按照长度排序
List43 = ["FHJDHF", "G", "GFG"]
NewList3 = sorted (List43,key=len)
Print (NEWLIST3)
?
#4.3 Copy "Face question"
#浅拷贝
#深拷贝
#a. From the memory point of view
#浅拷贝: Referencing "stack space"
List44 = [23,45,98]
List45 = List44
LIST45[1] = 100
Print (LIST44)
Print (LIST45)
Print (ID (list44) = = ID (list45))
?
?
#深拷贝: Memory "entity, heap space"
List51 = [23,45,98]
List52= list51.copy ()
LIST52[1] = 100
Print (LIST51)
Print (LIST52)
Print (ID (list51) = = ID (list52))

Two. Dictionaries

1. Concept:
Thinking problem: Saving scores for multiple students
Solution: Dictionary, the student as key, the results as value, to store, easy to find "one by one correspondence"
Nature: Also a container for storing data
Features: Data stored as key-value pairs, with the advantage of Quick Find
Note: Dictionaries are unordered
Features of key
:? A. The key in the dictionary must be unique
? B. The key in the dictionary must be immutable
? List is mutable and cannot function as key
? A tuple is immutable and can act as a key, a numeric type, and a string can act as key
2. Create:
syntax: dictionary name = {key1:value1,key2:value2 ...}
Code Demo:
#1. Creating a Dictionary
#创建一个空字典
Dict1 = {}
#创建有键值对的字典
Dict2 = {"Zhangsan": $, "Jack": 90}
Print (DICT2)
3. Method:
1 Get key: Syntax dictionary name. Key
2 Gets the value: syntax dictionary name. Value
3 Modify or add: Syntax: dictionary name [Key]=value, if there is a key to modify, otherwise add a new key value pair
4 Delete: Syntax: dictionary name. Pop (key) deletes the specified Popitem () when the last one in the dictionary is deleted

Python Learning path 04--list and dictionary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.