[Learn python from zero] 21. Tuples and dictionaries in Python

tuple

Python's tuples are similar to lists, except that the elements of the tuple cannot be modified. Use parentheses for tuples and square brackets for lists.

aTuple = ('et',77,99.9)
aTuple

1. Access tuples

insert image description here

Second, modify the tuple

insert image description here

Explanation: It is not allowed to modify the data of the tuple in python, including deleting the elements.

Three, count, index

index and count are used in the same way as in strings and lists

a = ('a', 'b', 'c', 'a', 'b')
a.index('a', 1, 3) # 注意是左闭右开区间
a.index('a', 1, 4)
a.count('b')
a.count('d')

4. Define a tuple with only one data

To define a tuple with only one element, you need to write a comma after the only element

a = (11)
type(a)
a = (11,)  # 只有一个元素的元组,必须要在元素后写一个逗号
type(a)

5. Swap the values ​​of two variables

The first way, using intermediate variables

a = 4
b = 5
c = 0

c = a
a = b
b = c
print(a)
print(b)

The second way is direct exchange.

a, b = 4, 5
a, b = b, a

print(a)
print(b)

dictionary introduction

1. Disadvantages of lists

When the stored data needs to be added and deleted dynamically, we generally use lists, but lists sometimes encounter some troubles.

nameList = ['xiaoZhang', '男', '木匠'];

nameList[2] = '铁匠'  

nameList = ['xiaoWang', 18, '男',  '铁匠']

nameList[3] = 'xiaoxiaoWang'

Is there a way to not only store multiple data, but also locate the required element when accessing the element is very convenient?

answer:

dictionary

2. The use of dictionaries

Define the format of the dictionary: {key 1: value 1, key 2: value 2, key 3: value 3, ..., key n: value n}

The variable info is a dictionary type:

info = {
    
    'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国上海'}
info['name']

illustrate:

  • Dictionaries, like lists, can also store multiple data
  • When looking for an element in the list, it is based on the subscript; when looking for an element in the dictionary, it is based on the 'name' (that is, the value in front of the colon: for example, 'name', 'id', 'sex')
  • Each element of the dictionary consists of 2 parts, key: value. For example 'name':'squad leader', 'name' is the key, 'squad leader' is the value
  • Keys can use immutable data types such as numbers, Boolean values, and tuples, but it is generally customary to use strings
  • The key in each dictionary is unique. If there are multiple keys, the subsequent value will overwrite the value corresponding to the previous key.
  • In custom:
    • Lists are more suitable for storing similar data such as multiple products, multiple names, and multiple times;
    • Dictionaries are more suitable for storing different information about a product, different information about a person, and such different data.

Advanced case

[Python] Python realizes the word guessing game-challenge your intelligence and luck!

[python] Python tkinter library implements GUI program for weight unit converter

[python] Use Selenium to get (2023 Blog Star) entries

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[Xiaobai must see] Python word cloud generator detailed analysis and code implementation

[Xiaobai must see] Python crawls an example of NBA player data

[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[Xiaobai must see] Python crawler data processing and visualization

[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory

[Must-see for Xiaobai] Use Python to generate a personalized list Word document

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

Geospatial data processing and visualization using geopandas and shapely (.shp)

Use selenium to crawl Maoyan movie list data

Detailed explanation of the principle and implementation of image enhancement algorithm Retinex

Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API

Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies

Getting started with crawlers (2): How to use regular expressions for data extraction and processing

Getting started with reptiles (1): Learn the basics and skills of reptiles

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

Python object-oriented programming basics and sample code

MySQL database operation guide: learn how to use Python to add, delete, modify and query operations

Python file operation guide: encoding, reading, writing and exception handling

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

Pandas data processing and analysis tutorial: from basics to actual combat

Detailed explanation of commonly used data types and related operations in Python

[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Use 4 regression methods to draw prediction result charts: vector regression, random forest regression, linear regression, K-nearest neighbor regression
** [Learn python from zero] 18. Detailed explanation of basic operations of Python lists (1) **

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132280140