Zero-based learning Python|Python advanced learning fifth day

​ Author homepage: Programming Compass

About the author: High-quality creator in the Java field, CSDN blog expert
, CSDN content partner, invited author of Nuggets, Alibaba Cloud blog expert, 51CTO invited author, many years of architect design experience, resident lecturer of Tencent classroom

Main content: Java project, Python project, front-end project, artificial intelligence and big data, resume template, learning materials, interview question bank, technical mutual assistance

Favorites, likes, don't get lost, it's good to follow the author

Get the source code at the end of the article

1. Dictionary

A dictionary is similar to a list and is also a variable sequence, but it is unordered and stores data in the form of key-value pairs, which is similar to the Map collection in Java.

The key of the dictionary is unique and immutable. Numbers, strings or tuples can be used as keys, but lists cannot be used as keys.

1.1 Creation and deletion of dictionaries

Basic syntax for dictionary creation:

dictionary = {
    
    'key':value,'key1':value1,....'keyn':valuen}

Creation of an empty dictionary:

dictionary = {
    
    }
dictionary = dict()

In addition to creating an empty dictionary, the dict() function can also quickly create a dictionary from existing data. There are mainly two forms:

1. Create a dictionary table through the mapping function

dictionary = dict(zip(list1,list2))
* dictionary 为字典名
* zip()函数:用于将多个列表或元组对应位置的元素组合为元组,并返回包含这些内容的zip对象。如果想得到元组,可以使用tuple()函数将zip对象转换为元组;如果想得到列表,则可以使用list()函数将其转换为列表。
* list1:一个列表,用于指定要生成字典的键
* list2:一个列表,用于指定要生成字典的值
* 返回值:如果list1和list2长度不同,则与最短的列表长度相同

Example:

#示例1  通过dict()进行字典创建
name = ['马丽','沈腾','岳云鹏']  #作为键的列表
sign = ['喜剧','小品','相声'] #作为值的列表
dictionary = dict(zip(name,sign)) #转换为字典
print(dictionary)

2. Create a dictionary with a given key-value pair

dictionary = dict(key1=value1,key2=value2,...keyn=valuen)
* dictionary 为字典名
* key1、key2...keyn:表示元素的键,必须是唯一的,并且不可变,可以是字符串、数字或元组。
* value1、value2..valuen:表示元素的值,可以是任何数据类型,不是必须唯一。

Example:

dictionary = dict(邓肯='石佛',吉诺比利='妖刀',帕克='跑车')
print(dictionary)

This meal can also create an empty dictionary through the fromkeys method of the dict object:

dictionary = dict.fromkeys(list1)
* dictionary 表示字典名称
* list1 作为字典的键的列表

Example:

name_list =['邓肯','吉诺比利','帕克']
dictionary = dict.fromkeys(name_list)
print(dictionary)

Alternatively, dictionaries can be created from existing tuples and lists:

name_tuple =('邓肯','吉诺比利','帕克')
sign = ['石佛','妖刀','跑车']
dict1 = {name_tuple:sign}
print(dict1)

Thinking: If the above example is reversed, is it feasible to use the list as the key and the tuple as the value?

Dictionary deletion:

del dictionary

Empty dictionary: empty the dictionary elements into an empty dictionary

dictionary.clear()

1.2 Accessing dictionaries through key-value pairs

dictionary = {'邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
print(dictionary['帕克'])

In this way, if the KEY does not exist, an exception will be reported.

It can be solved by judging:

dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
if '帕克' in list(dictionary.keys()):
   print(dictionary['帕克'])
else:
   print('查无此人')

The get method is recommended in Python to solve such problems:

dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
print(dictionary.get('帕克','查无此人'))

1.3 Traversing the dictionary

You can get all the key-value pairs of the dictionary through the items() method of the dictionary, and then extract them cyclically:

dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
for item in dictionary.items():
   print(item)

If you want to get the KEY and VALUE of each key-value pair in more detail:

dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
for key,value in dictionary.items():
   print(key,'绰号是',value)

The dictionary object also provides values() and keys() to get the values ​​and keys of the dictionary, and then traverse to obtain:

dictionary = {'邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
for key in dictionary.keys():
    print('key:',key)
    print('value:',dictionary.get(key,'查无此人'))
dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
for value in dictionary.values():
   print(value)

1.4 Adding, modifying and deleting elements

Dictionaries are mutable sequences, so 'key-value pairs' can be added to them at any time as needed.

dictionary[key]=value

Example:

dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
dictionary['乔丹']='飞人'
print(dictionary)

You can modify the existing key value: the key is unique, and the added value will overwrite the previous value

dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
dictionary['邓肯']='大佛'
print(dictionary)

You can use del to delete the key value:

dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
del dictionary['邓肯']
print(dictionary)

If you delete a key value that does not exist, an error will be reported, and you can judge the processing:

dictionary = {
    
    '邓肯':'石佛','吉诺比利':'妖刀','帕克':'跑车'}
if '邓肯' in dictionary:
   del dictionary['邓肯']
print(dictionary)

1.5 Dictionary comprehension

Use dictionary comprehensions to quickly generate a dictionary.

import random
randomdict = {
    
    i:random.randint(10,100) for i in range(1,5)}
print('生成的字典为:',randomdict)

output:

生成的字典为: {1: 39, 2: 49, 3: 74, 4: 43}

Two, collection

Sets are used to store non-heavy elements. It is unordered. It has two types: variable set (set) and immutable set (frozenset). This time we only talk about set, which is actually very similar to Java's set. Its main application scenario is to save a series of unique element data.

2.1 Collection creation

1. Use { } directly to create:

setname = {element1,element2,....elementn}

Collection element types are not restricted:

set1 = {'str1','str2','str3'}
set2 = {1,2,3,4,5,6}
set3 = {'Python',30,('人生苦短','我学Python')}

2. Use the set() function to create a collection

setname = set(iteration)
* setname  集合名字
* iteartion 可迭代的对象,比如:列表、元组、range对象等,如果是字符串,则返回包含不重复的字符集合

Example:

set1 = set('命运给我们的不是失望之酒,而是希望之杯。')
set2 = set([1.45,3.22,4,6])
set3 = set(('人生苦短','我学Python'))
print(set1)
print(set2)
print(set3)

In Python, it is recommended to use set() to create collections.

If you are creating an empty collection, you can only use set() instead of {}, because {} is used to create an empty dictionary.

2.2 Addition and deletion of collections

Collection additions:

setname.add(element)
* 添加的元素只能是数字、字符串或布称类型的True和False,不能使用列表、元组等可迭代对象

Example:

set1 = {'str1','str2','str3'}
set1.add('str4')
print(set1)

Collection deletion:

You can delete an entire collection with del, or remove elements with pop() and remove(). Collections can also be emptied using clear().

#示例 集合的删除
set1 = {
    
    'str1','str2','str3'}
set1.remove('str3')  #移除指定的元素
set1.pop()   #移除集合左边第一个
print(set1)

2.3 Intersection, union and difference operations of sets

The intersection operation uses the '&' symbol, which is used to calculate the repeated parts of two sets.

The union operation uses '|' to calculate the union of two sets (remove duplicates)

The difference operation uses '-' to remove elements that both sides have

Example:

set1 = {
    
    'java','python','c++'}
set2 = {
    
    'python','html','css'}
print('交集运算:',set1&set2)
print('并集运算:',set1|set2)
print('差集运算:',set1-set2)

Output result:

交集运算: {'python'}
并集运算: {'python', 'html', 'c++', 'java', 'css'}
差集运算: {'c++', 'java'}

Lists, tuples, dictionaries, and sets of sequences have been explained so far. Let's summarize their differences:

insert image description here

Guess you like

Origin blog.csdn.net/whirlwind526/article/details/132376801