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

Python notes 10 tuples & dictionaries & Collections

編輯:Python

One 、 Tuples 【 understand 】

1. Concept

Similar to the list , It is essentially an ordered set

The difference between tuples and lists :

a. list :[] Tuples :()
b. The elements in the list can be added or deleted , however , Elements in tuples cannot be modified 【 Elements : Once initialized , Will not change 】

2. Compare with list

Create a list of :

 Create an empty list :list1 = []
Create a list with elements :list1 = [ Elements 1, Elements 2,.....]

Creating a tuple

 Create an empty tuple :tuple1 = ()
Create some tuples :tuple1 = ( Elements 1, Elements 2,....)

3. Tuple operation

# 1. Concept
"""
list : A list is an ordered , Variable , Can store duplicate elements , A collection that can store different types of data
Tuples : Tuples are a kind of ordered , Immutable , Can store duplicate elements , A collection that can store different types of data
"""
# 2. Definition
l1 = [34,5,67,5,5,True,'abc']
print(l1,type(l1)) # <class 'list'>
t1 = (34,5,67,5,5,True,'abc')
print(t1,type(t1)) # <class 'tuple'>
# Be careful : When there is only one element in a tuple , You need to add a comma after the element , To disambiguate
l2 = [10]
print(l2,type(l2)) # <class 'list'>
# t2 = (10) # Equivalent to t2 = 10
# print(t2,type(t2)) # <class 'int'>
t2 = (10,)
print(t2,type(t2)) # (10,) <class 'tuple'>
# 3. Element access
# a. obtain
print(l1[0])
print(t1[0])
print(l1[-1])
print(t1[-1])
# Be careful : Tuples and lists have the same index , Both have positive and negative indexes , They can't cross the border
# print(l1[10]) # IndexError: list index out of range
# print(t1[10]) # IndexError: tuple index out of range
# b. modify
# Be careful : Once the tuple is defined , Only one of the elements can be obtained , Cannot modify element
l1[0] = 100
print(l1)
# t1[0] = 100 # TypeError: 'tuple' object does not support Support item Elements assignment assignment
# 【 Interview questions 】
tuple1 = (3,5,'aga',False,[1,2,3])
tuple1[-1][1] = 100 # What is modified is the list
print(tuple1) # (3, 5, 'aga', False, [1, 100, 3])
# 4. Traverse
for ele in t1:
print(ele)
for i in range(len(t1)):
print(i,t1[i])
for i,ele in enumerate(t1):
print(i,ele)
# 5. system function
# Be careful : Tuples are immutable , Therefore, tuples have no system functions related to addition, deletion and modification
# a.len()
print(len(t1))
# b.max(0/min()
t1 = (34,5,67,5,5)
print(max(t1))
print(min(t1))
# c.index()
print(t1.index(5))
# d.count()
print(t1.count(5))
# e.list()/tuple(): Conversion between lists and tuples
t1 = (34,5,67,5,5)
print(t1,type(t1))
l1 = list(t1)
print(l1,type(l1))
t2 = tuple(l1)
print(t2,type(t2))
# 6. The meaning of tuples
"""
a. In actual project development , Because the list is relatively flexible , You can add, delete, modify, and query , So there are many lists
b. In multiprocessing and multithreading , Generally, you need data that cannot be modified at will , Tuples are more powerful than lists
"""

Two 、 Dictionaries 【 Focus on mastering 】

1. Concept

Disadvantages of using lists and tuples : When the stored data needs to be added dynamically 、 When deleting , We usually use lists , But the list sometimes has some trouble

Solution : It can store multiple data , It can also easily locate the required element when accessing the element , Use dictionary

# 1. demand : Storage 5 Personal age , Get Zhang San's age
# Use lists or tuples to store , Can store multiple data , Because lists and tuples are ordered , Elements can only be retrieved by index
# however , If you want to locate the age of Zhang San , Unable to locate
age_list = [34,6,22,46,10] # Variable , You can add, delete, or modify
age_tuple = (34,6,22,46,10) # Immutable , Can't modify
print(age_list[1])
print(age_tuple[1])
# Use a dictionary to store
age_dict = {' Xiao Ming ':34," Zhang San ":6,' Xiao Wang ':22,' Lao zhang ':46," Li Si ":10}
age = age_dict[' Zhang San ']
print(age)
# 2. Scenarios used
# list : If you need to store data of the same type , List of suggestions
list1 = [' Zhang San ',' Li Si ','jack']
score_list = [66,100,56]
# Dictionaries : You can store different information about the same object perhaps Need to accurately locate a certain data , Suggested Dictionary
age_dict = {' Xiao Ming ':34," Zhang San ":6,' Xiao Wang ':22,' Lao zhang ':46," Li Si ":10}
info_dict = {'name':" Zhang San ",'age':18,'hobby':" Basketball "}
"""
【 Interview questions 】: Brief list , Tuples , Dictionaries , The difference between sets and strings
The essence of the list :list, It's an orderly , Variable , Can store duplicate elements , Different types of collections can be stored
The essence of tuples :tuple, It's an orderly , Immutable , Can store duplicate elements , Different types of collections can be stored
The essence of a dictionary :dict, It's an orderly 【Python3.7 after 】, Variable ,key Not to be repeated ,
however value Can be repeated ,key Can only be immutable data types ,vlue Can be any type of aggregate
The essence of set :set, It's a kind of disorder , Variable , Cannot store duplicate elements , Different types of collections can be stored
The nature of strings :str, It's an orderly , Immutable , A collection that can store duplicate characters
"""

2. Definition dictionary

grammar :{ key 1: value 1, key 2: value 2, key 3: value 3, …, key n: value n}

explain :

  • Dictionaries are like lists , Can be used to store multiple data
  • When looking for an element in the list , It's based on subscripts ; When looking for an element in a dictionary , It's based on ’ name ’( It's a colon : The previous value , For example, in the code above ’name’、‘id’、‘sex’)
  • Every element in the dictionary consists of 2 Part of it is made up of , key : value . for example ‘name’:‘ Monitor of the class ’ ,'name’ As the key ,' Monitor of the class ’ Value
  • Keys can use numbers 、 Boolean value 、 Tuples , String and other immutable data types , But it's common to use strings , Remember not to use variable data types such as lists , The value can be any type of data
  • In every dictionary key It's all unique , If there are multiple identical key, hinder value It will cover the previous value, however value Can be repeated

Get used to using scenarios :

  • Lists are more suitable for storing similar data , For example, multiple products 、 Multiple names 、 Multiple times

  • Dictionaries are more suitable for storing different data , For example, different information about a product 、 Different information about a person

    【 Interview questions 】 How to define a dictionary , List at least two ways

    1.

    dict1 = {‘name’:“ Zhang San ”,‘age’:18,‘hobby’:“ Basketball ”}
    print(dict1)

    2. *****

    dict2 = {}
    dict2[‘a’] = 100 # Add key value pair
    dict2[‘b’] = 200
    print(dict2)

    3.

    int(x) float(x) str() bool() list() tuple() dict() set()

    dict(key1=value1,key2=value2…): Must be name=value The way to transmit value , and name It can only be a variable

    dict3 = dict(a = 10,b = 20,c = 30)
    print(dict3)

    dict31 = {1:100,2:200}
    print(dict31)

    dict31 = dict(1=100,2=200)

    print(dict31)

    4.

    dict(iterable):iterable It has to be two-dimensional

    working principle :

    d = {}

    for k,v in [[‘x’,11],[‘y’,22],[‘z’,33]]:

    d[k] = v

    print(d)

    dict4 = dict([[‘x’,11],[‘y’,22],[‘z’,33]])
    print(dict4)
    dict4 = dict([(‘x’,11),(‘y’,22),(‘z’,33)])
    print(dict4)
    dict4 = dict(((‘x’,11),(‘y’,22),(‘z’,33)))
    print(dict4)

    5. ******

    dict(zip( be-all key, be-all value))

    dict5 = dict(zip([‘name’,‘age’,‘score’],[‘tom’,10,100]))
    print(dict5)
    dict5 = dict(zip((‘name’,‘age’,‘score’),(‘tom’,10,100)))
    print(dict5)
    dict5 = dict(zip((‘name’,‘age’,‘score’),[‘tom’,10,100]))
    print(dict5)
    dict5 = dict(zip([‘name’,‘age’,‘score’,‘gender’],[‘tom’,10,100]))
    print(dict5)
    dict5 = dict(zip([‘name’,‘age’,‘score’],[‘tom’,10,100,46,67,8,8]))
    print(dict5)

    Be careful : No matter how you define the dictionary , In the dictionary key Are immutable data types

    “”"
    Immutable type :int float bool str tuple
    Variable data types :list dict set
    “”"

3. Basic use

# list / Tuples : list / Tuples [ Indexes ]
# Dictionaries : Dictionaries [key]
# 1. obtain
# a.
# In every dictionary key It's all unique , If there are multiple identical key, hinder value It will cover the previous value
d1 = {'a':10,'b':20,"a":30}
print(d1) # {'a': 30, 'b': 20}
# b. Mode one : Dictionaries [key]
dict1 = {'name':" Zhang San ",'age':18,'hobby':" Basketball "}
print(dict1)
print(dict1['age'])
# Be careful : If key non-existent , Can't get
# print(dict1['score']) # KeyError: 'score'
# Optimize
if 'score' in dict1:
print(dict1['score'])
else:
print("key non-existent ")
# b. Mode two : Dictionaries .get(key) ******
# Be careful : If key There is , Then get the corresponding value , If key non-existent , Then return to None
print(dict1.get('age'))
print(dict1.get('score'))
# 2. modify , The main purpose is to modify value
# grammar : Dictionaries [key] = value, effect : If key There is , It means to modify the corresponding value , however , If key non-existent , It means adding key value pairs
print(dict1)
dict1['age'] = 66
print(dict1)
dict1['score'] = 100
print(dict1)
# 3. Ergodic dictionary
# a *******
for key in dict1:
print(key,dict1[key])
# b.
print(dict1.keys()) # Get all the... In the dictionary key
for key in dict1.keys():
print(key,dict1[key])
# c.
print(dict1.values())
for value in dict1.values():
print(value)
# d. *******
print(dict1.items())
for key,value in dict1.items():
print(key,value)
# practice 1: The following dictionaries are known , Get Zhang San's age , Whether the obtained results are unique ? only
age_dict = {' Xiao Ming ':34," Zhang San ":6,' Xiao Wang ':22,' Lao zhang ':6," Li Si ":6}
age = age_dict[' Zhang San ']
print(age) # 6
# practice 2: The following dictionaries are known , The age of acquisition is 6 The name of the student , Whether the obtained results are unique ? not always
age_dict = {' Xiao Ming ':34," Zhang San ":6,' Xiao Wang ':22,' Lao zhang ':6," Li Si ":6}
for key,value in age_dict.items():
if value == 6:
print(key)
"""
summary :
adopt key Acquired value Is the only one. , however , adopt value Acquired key Not necessarily the only
"""

4. Dictionary system functions

# One 、 increase
dict1 = {'a':10,'b':20}
print(dict1)
# 1. Dictionaries [key] = value, When key When there is no , Indicates adding key value pairs *****
# dict1['c'] = 30
# print(dict1)
# 2.update(): to update , Merge dictionaries , Add the key value pairs in the specified dictionary to the original dictionary ****** It mainly appears in the interview questions
# dict1.update(dict2): take dict2 The key value pairs in are added to dict1 in
new_dict = {'x':34,'y':75}
dict1.update(new_dict)
print(dict1)
print(new_dict)
# 3.setdefault(key,default): Add key value pairs by setting default values , understand
dict1 = {'a':10,'b':20}
print(dict1)
# a.default Omit , Add... To the specified dictionary :key:None
dict1.setdefault('abc')
print(dict1) # {'a': 10, 'b': 20, 'abc': None}
# b.default Not omitted , Add... To the specified dictionary :key:default
dict1.setdefault('xyz',88)
print(dict1) # {'a': 10, 'b': 20, 'abc': None, 'xyz': 88}
# Two 、 Delete
# 1.pop(key): eject , Delete the specified key Corresponding key value pair , ********
# 【 How it works : Removes the specified key value pair from the dictionary , But in memory 】
dict1 = {'name':" Zhang San ",'age':18,'hobby':" Basketball "}
print(dict1)
r = dict1.pop('age') # pop Similar to the usage in the list , Return deleted data
print(dict1)
print(r)
# 2.popitem(): stay Python3.7 Before , Means to delete a pair randomly , stay 3.7 after , Delete the last pair
dict1 = {'name':" Zhang San ",'age':18,'hobby':" Basketball "}
print(dict1)
dict1.popitem()
print(dict1)
# 3.clear()
dict1 = {'name':" Zhang San ",'age':18,'hobby':" Basketball "}
print(dict1)
dict1.clear()
print(dict1)
# 4.del
dict1 = {'name':" Zhang San ",'age':18,'hobby':" Basketball "}
print(dict1)
del dict1['age']
print(dict1)
# del dict1 # Delete Dictionary
# 3、 ... and 、 Change
dict1 = {'name':" Zhang San ",'age':18,'hobby':" Basketball "}
print(dict1)
dict1['age'] = 66
print(dict1)
# Four 、 check
print(len(dict1)) # Get the logarithm of the key value pair
print(dict1.keys())
print(dict1.values())
print(dict1.items())
# 5、 ... and 、 other
# But for variable data types , There are copy()
# Dictionaries can also be used copy(),copy.copy(),copy.deepcopy()
# Dictionaries also follow the same characteristics of deep and shallow copies as lists

5. Dictionary derivation

"""
List derivation :[ Law of elements for loop if sentence ]
Dictionary derivation :{key:value for loop if sentence }
"""
# 1. Known dictionaries d1 = {'a':10,'b':20}, Generate a new dictionary ,{10:'a',20:'b'}
d1 = {'a':10,'b':20}
# Mode one
d2 = {}
for k in d1:
d2[d1[k]] = k
print(d2)
# Mode two
d2 = {}
for k,v in d1.items():
d2[v] = k
print(d2)
# Mode three
d2 = dict(zip(d1.values(),d1.keys()))
print(d2)
# Mode 4
d2 = {v:k for k,v in d1.items()}
print(d2)
# Methods five :
d2 = {d1[k]:k for k in d1}
print(d2)
# 2. Generate Dictionary :{0:0,2:4,4:16,6:36,8:64}
dict2 = {i:i ** 2 for i in range(0,9,2)}
print(dict2)
dict2 = {i:i ** 2 for i in range(0,10) if i % 2 == 0}
print(dict2)
# 3. Same as list derivation , In dictionary derivation , You can also use multiple for Or more if, From left to right, the nested relationships are represented
list1 = [a + b for a in 'xyz' for b in '123']
print(list1) # ['x1', 'x2', 'x3', 'y1', 'y2', 'y3', 'z1', 'z2', 'z3']
dict1 = {a:b for a in 'xyz' for b in '123'}
print(dict1) # {'x': '3', 'y': '3', 'z': '3'}

3、 ... and 、 aggregate 【 understand 】

1. Concept

Python The set in is consistent with the set in mathematics , Duplicate elements are not allowed , And it can intersect 、 Combine 、 Subtraction and so on

set And dict similar , But with the dict The difference is that it's just a group key Set , Do not store value

The essence : A collection of unordered and non repeating elements

Express :{}, Be careful : If used directly {} It means dictionary by default

2. establish

# 1. Concept
"""
【 Interview questions 】: Brief list , Tuples , Dictionaries , The difference between sets and strings
The essence of the list :list, It's an orderly , Variable , Can store duplicate elements , Different types of collections can be stored
The essence of tuples :tuple, It's an orderly , Immutable , Can store duplicate elements , Different types of collections can be stored
The essence of a dictionary :dict, It's an orderly 【Python3.7 after 】, Variable ,key Not to be repeated ,
however value Can be repeated ,key Can only be immutable data types ,vlue Can be any type of aggregate
The essence of set :set, It's a kind of disorder , Variable , Cannot store duplicate elements , Different types of collections can be stored
The nature of strings :str, It's an orderly , Immutable , A collection that can store duplicate characters
"""
# 2. Definition
# a. Define an empty set
# {} The default means dictionary
dict1 = {}
print(type(dict1))
set1 = set()
print(set1)
# b. Define a nonempty set
set2 = {3,5,6}
print(set2,type(set2))
# c. duplicate removal
set3 = {3,3,3,3,4,5,6,6,6,6}
print(set3)
# d. disorder
set4 = {7,2,45,2,6,7,8,9,10}
print(set4)
# practice : To duplicate a repeating element in a list
list1 = [45,67,7,8,2,2,2]
list2 = list(set(list1))
print(list2)

3. Operation between sets

# 3. operation
s1 = {1,2,3}
s2 = {3,4,5}
# 3.1 Symbol
# a. intersection
print(s1 & s2) # {3}
# b. Combine
print(s1 | s2) # {1, 2, 3, 4, 5}
# c. Difference set
print(s1 - s2) # {1, 2}
# 3.2 system function
# a. intersection
r1 = s1.intersection(s2) # {3}
print(r1)
# b. Combine
r1 = s1.union(s2) # {1, 2, 3, 4, 5}
print(r1)
# c. Difference set
r1 = s1.difference(s2)
print(r1) # {1, 2}

4. Collect system functions

# The connection between sets and dictionaries : A collection is equivalent to storing the key
# One 、 increase
# 1.add(x),x Can only be immutable data types , If x Is an iterative object , Then add... As a whole
s1 = {11,22,33}
print(s1)
s1.add(44)
print(s1)
s1.add("abc")
print(s1)
s1.add(True)
print(s1)
s1.add((55,66))
print(s1)
# s1.add([55,66]) # TypeError: unhashable type: 'list'
# s1.add({'a':10}) # TypeError: unhashable type: 'dict'
print("*" * 30)
# 2.update(x),x Can only be iteratable objects , Only the elements in the iteratable object will be added 【 Smash and join 】
# Iteratable object :list,tuple,dict,set,set,range() Equal container
s1 = {11,22,33}
print(s1)
# s1.update(44) # TypeError: 'int' object is not iterable Iteratable object
s1.update("abc")
print(s1)
# s1.update(True) # TypeError: 'bool' object is not iterable
s1.update((55,66))
print(s1)
s1.update([77,88])
print(s1)
s1.update({'x':10,'y':20}) # Be careful : If x It's a dictionary , Only add key
print(s1)
# Two 、 Delete
# 1.remove(x):x Indicates the element to be deleted ******
s1 = {11,22,33,4,78,79}
print(s1)
s1.remove(33)
print(s1)
# s1.remove(100) # KeyError: 100
# 2.pop(): Because sets are unordered , therefore pop It means to randomly delete a
s1 = {11,22,33,4,78,79}
print(s1)
s1.pop()
print(s1)
# 3.discard(x): and remove The usage is the same , If the deleted element does not exist ,remove Will report a mistake , however discard No mistake. *****
s1 = {11,22,33,4,78,79}
print(s1)
s1.discard(33)
print(s1)
s1.discard(100)
# 4.clear(): Empty
s1.clear()
print(s1) # set()
# 3、 ... and 、 check
s1 = {11,22,33,4,78,79}
s2 = s1.copy()
print(len(s1))
print(max(s1))
print(min(s1))
# int()/float()/bool()/list()/tuple()/dict()/set()

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