[Learn python from zero] 19. Application of looping through lists and list nesting

List loop traversal

1. Use while loop

In order to more efficiently output each data of the list, you can use a loop to complete

namesList = ['xiaoWang','xiaoZhang','xiaoHua']
length = len(namesList)  # 获取列表长度
i = 0
while i<length:
    print(namesList[i])
    i+=1

result:

xiaoWang
xiaoZhang
xiaoHua

2. Use a for loop

The while loop is a basic way of traversing list data, but the most common and easiest way is to use the for loop

namesList = ['xiaoWang','xiaoZhang','xiaoHua']
for name in namesList:
    print(name)

result:

xiaoWang
xiaoZhang
xiaoHua

3. Swap the values ​​of 2 variables

use intermediate variables

a = 4
b = 5
c = 0

c = a
a = b
b = c

print(a)
print(b)

practise

Manually implement bubble sort (difficult)

nums = [5, 1, 7, 6, 8, 2, 4, 3]

for j in range(0, len(nums) - 1):
   for i in range(0, len(nums) - 1 - j):
       if nums[i] > nums[i + 1]:
           a = nums[i]
           nums[i] = nums[i+1]
           nums[i+1] = a

print(nums)

There is a list names, save a group of names names=['zhangsan','lisi','chris','jerry','henry'], and then let the user enter a name, if the name exists in the list, prompt The user name already exists; if the name does not exist in the list, the name is added to the list.

1. List nesting

Similar to nesting of while loops, lists also support nesting

The elements in a list are another list, then this is the nesting of lists

Here we focus on how to operate the nested list

schoolNames = [
    [1, 2, 3],
    [11, 22, 33],
    [111, 222, 333]
]
schoolNames[1][2]  # 获取数字 33
schoolNames[1][2] = 'abc'  # 把 33 修改为 'abc'
schoolNames[1][2][2]  # 获取 'abc' 里的字符c

That is to say, to operate nested lists, just use the subscript of the element to be operated as a variable name.

2. Application

A school has 3 offices, and now there are 8 teachers who are waiting for the allocation of seats. Please write a program to complete the random allocation

import random

# 定义一个列表用来保存3个办公室
offices = [[],[],[]]

# 定义一个列表用来存储8位老师的名字
names = ['A','B','C','D','E','F','G','H']

i = 0
for name in names:
    index = random.randint(0,2)    
    offices[index].append(name)

i = 1
for tempNames in offices:
    print('办公室%d的人数为:%d'%(i,len(tempNames)))
    i+=1
    for name in tempNames:
        print("%s"%name,end='')
    print("\n")
    print("-"*20)

The result of the operation is as follows:
insert image description here

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/132275772