[Python basics] day06-Python list and tuple learning and use, list loop traversal and common operations (list comprehensive application-random allocation of offices)

curriculum schedule

the goal

  • Application scenarios of the list
  • List format
  • Common operations for lists
  • Loop traversal of the list
  • Nested use of lists

1. Application scenarios of the list

Thinking: How to write a stored program with a person's name (TOM)?

Answer: Variables.

Thinking: If there are 100 students in a class, and everyone's name must be stored, how should the program be written? Declare 100 variables?

Answer: The list is enough, and the list can store multiple data at one time.

2. List format

[数据1, 数据2, 数据3, 数据4......]

The list can store multiple data at once, and can be of different data types.

3. Common operations of the list

The function of the list is to store multiple data at one time, and the programmers can perform operations on these data: add, delete, modify, and check.

3.1 Find

3.1.1 Subscript

name_list = ['Tom', 'Lily', 'Rose']

print(name_list[0])  # Tom
print(name_list[1])  # Lily
print(name_list[2])  # Rose

3.1.2 Function

  • index(): Returns the index of the location of the specified data.
  1. grammar
列表序列.index(数据, 开始位置下标, 结束位置下标)
  1. Quick experience
name_list = ['Tom', 'Lily', 'Rose']

print(name_list.index('Lily', 0, 2))  # 1

Note: If the searched data does not exist, an error will be reported.

  • count(): Count the number of times the specified data appears in the current list.
name_list = ['Tom', 'Lily', 'Rose']

print(name_list.count('Lily'))  # 1
  • len(): The length of the access list, that is, the number of data in the list.
name_list = ['Tom', 'Lily', 'Rose']

print(len(name_list))  # 3

3.1.3 Determine if it exists

  • in: Judge that the specified data is in a certain list sequence, if it is returning True, otherwise it returns False
name_list = ['Tom', 'Lily', 'Rose']

# 结果:True
print('Lily' in name_list)

# 结果:False
print('Lilys' in name_list)
  • not in: Judge that the specified data is not in a certain list sequence, if not in, return True, otherwise return False
name_list = ['Tom', 'Lily', 'Rose']

# 结果:False
print('Lily' not in name_list)

# 结果:True
print('Lilys' not in name_list)
  • Experience case

Requirement: Find out whether the name entered by the user already exists.

name_list = ['Tom', 'Lily', 'Rose']

name = input('请输入您要搜索的名字:')

if name in name_list:
    print(f'您输入的名字是{name}, 名字已经存在')
else:
    print(f'您输入的名字是{name}, 名字不存在')

3.2 Increase

Function: Add specified data to the list.

  • append(): Append data to the end of the list.
  1. grammar
列表序列.append(数据)
  1. Experience
name_list = ['Tom', 'Lily', 'Rose']

name_list.append('xiaoming')

# 结果:['Tom', 'Lily', 'Rose', 'xiaoming']
print(name_list)

result:
Insert picture description here

When adding data to the list, the specified data is directly added to the original list, that is, the original list is modified, so the list is variable type data.

  1. important point

If the data appended by append() is a sequence , append the entire sequence to the list

name_list = ['Tom', 'Lily', 'Rose']

name_list.append(['xiaoming', 'xiaohong'])

# 结果:['Tom', 'Lily', 'Rose', ['xiaoming', 'xiaohong']]
print(name_list)
  • extend(): append data to the end of the list . If the data is a sequence, add the data of this sequence to the list one by one.
  1. grammar
列表序列.extend(数据)
  1. Quick experience

    2.1 Single data

name_list = ['Tom', 'Lily', 'Rose']

name_list.extend('xiaoming')

# 结果:['Tom', 'Lily', 'Rose', 'x', 'i', 'a', 'o', 'm', 'i', 'n', 'g']
print(name_list)

​ 2.2 Sequence data

name_list = ['Tom', 'Lily', 'Rose']

name_list.extend(['xiaoming', 'xiaohong'])

# 结果:['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaohong']
print(name_list)
  • insert(): Add data at the specified location.
  1. grammar
列表序列.insert(位置下标, 数据)
  1. Quick experience
name_list = ['Tom', 'Lily', 'Rose']

name_list.insert(1, 'xiaoming')

# 结果:['Tom', 'xiaoming', 'Lily', 'Rose']
print(name_list)

3.3 Delete

  • of the
  1. grammar
del 目标
  1. Quick experience

    2.1 Delete list

name_list = ['Tom', 'Lily', 'Rose']

# 结果:报错提示:name 'name_list' is not defined
del name_list
print(name_list)

​ 2.2 Delete specified data

name_list = ['Tom', 'Lily', 'Rose']

del name_list[0]

# 结果:['Lily', 'Rose']
print(name_list)
  • pop(): Delete the data of the specified subscript (the default is the last one), and return the data.
  1. grammar
列表序列.pop(下标)
  1. Quick experience
name_list = ['Tom', 'Lily', 'Rose']

del_name = name_list.pop(1)

# 结果:Lily
print(del_name)

# 结果:['Tom', 'Rose']
print(name_list)
  • remove(): Remove the first match of a certain data in the list.
  1. grammar
列表序列.remove(数据)
  1. Quick experience
name_list = ['Tom', 'Lily', 'Rose']

name_list.remove('Rose')

# 结果:['Tom', 'Lily']
print(name_list)
  • clear(): Clear the list
name_list = ['Tom', 'Lily', 'Rose']

name_list.clear()
print(name_list) # 结果: []

3.4 Modification

  • Modify the specified subscript data
name_list = ['Tom', 'Lily', 'Rose']

name_list[0] = 'aaa'

# 结果:['aaa', 'Lily', 'Rose']
print(name_list)
  • Reverse: reverse()
num_list = [1, 5, 2, 3, 6, 8]

num_list.reverse()

# 结果:[8, 6, 3, 2, 5, 1]
print(num_list)
  • Sort: sort()
  1. grammar
列表序列.sort( key=None, reverse=False)

Note: reverse means sorting rules, reverse = True descending order, reverse = False ascending order (default)

  1. Quick experience
num_list = [1, 5, 2, 3, 6, 8]

num_list.sort()

# 结果:[1, 2, 3, 5, 6, 8]
print(num_list)

3.5 Copy

Function: copy()

name_list = ['Tom', 'Lily', 'Rose']

name_li2 = name_list.copy()

# 结果:['Tom', 'Lily', 'Rose']
print(name_li2)

4. Loop traversal of the list

Requirement: Print each data in the list in turn.

4.1 while

  • Code
name_list = ['Tom', 'Lily', 'Rose']

i = 0
while i < len(name_list):
    print(name_list[i])
    i += 1
  • Results of the

Insert picture description here

4.2 for

  • Code
name_list = ['Tom', 'Lily', 'Rose']

for i in name_list:
    print(i)
  • Results of the

Insert picture description here

Five. List nesting

The so-called list nesting refers to a list containing other sub-lists.

Application scenario: It is necessary to store the names of students in classes 1, 2, and 3, and the names of students in each class are in a list.

name_list = [['小明', '小红', '小绿'], ['Tom', 'Lily', 'Rose'], ['张三', '李四', '王五']]

Thinking: How to find the data "Li Si"?

# 第一步:按下标查找到李四所在的列表
print(name_list[2])

# 第二步:从李四所在的列表里面,再按下标找到数据李四
print(name_list[2][1])

6. Comprehensive Application-Random Assignment of Offices

Requirements: There are three offices, 8 teachers, 8 teachers are randomly assigned to 3 offices

"""
需求:有三个办公室,8位老师,8位老师随机分配到3个办公室

步骤:
1.准备数据
    8位老师---列表
    3个办公室---列表
2.分配老师到办公室
    随机分配
    就是把老师的名字写到办公室列表---办公室追加老师的名字
3,验证是否分配成功
    打印办公室详细信息,每个办公室的人数相对应老师的名字
"""

import random
# 1.准备数据
teachers = ['A','B','C','D','E','F','G','H']
offices = [[],[],[]]

# 2.分配老师到办公室--取每个老师到办公室列表--遍历老师列表数据
for name in teachers:
    # 列表追加数据 -- append(选中)  extend insert不适合
    # xx[0] -- 不能指定某个具体下标,要随机选中办公室编号
    num = random.randint(0,2)
    offices[num].append(name)
# 给每个办公室编号1,2,3
i = 1
# 验证是否分配成功
for office in offices:
    # 打印办公室人数 -- 列表长度len()
    print(f'办公室{i}的人数是{len(office)},老师分别是:')
    # 打印老师名字,每个办公室人数不一定 -- 遍历 -- 子列表
    for name in office:
        print(name)
    i += 1

result:
Insert picture description here

Seven. List summary

  • List format
[数据1, 数据2, 数据3]
  • Common methods of operation
    • index()
    • len ()
    • append()
    • pop()
    • remove()
  • List nesting
name_list = [['小明', '小红', '小绿'], ['Tom', 'Lily', 'Rose'], ['张三', '李四', '王五']]
name_list[2][1]

Tuple

the goal

  • Application scenarios of tuples
  • Define tuple
  • Common operations on tuples

1. Application scenarios of tuples

Thinking: If you want to store multiple data, but these data cannot be modified, how to do it?

Answer: List? The list can store multiple data at once, but the data in the list can be changed.

num_list = [10, 20, 30]
num_list[0] = 100

A tuple can store multiple data, and the data in the tuple cannot be modified.

Two. Define tuples

Tuple features: define the use of tuplesParenthesesAndcommaSeparate each data, the data can be of different data types.

# 多个数据元组
t1 = (10, 20, 30)

# 单个数据元组
t2 = (10,)

Note: If the defined tuple has only one data, then it is better to add a comma after the data, otherwise the data type is the only data type of this data

t2 = (10,)
print(type(t2))  # tuple

t3 = (20)
print(type(t3))  # int

t4 = ('hello')
print(type(t4))  # str

3. Common operations of tuples

Tuple data does not support modification, but only supports search, as follows:

  • Press the index to find the data
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1[0])  # aa
  • index(): Find a certain data, if the data exists, return the corresponding subscript, otherwise report an error, the syntax is the same as the index method of lists and strings.
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.index('aa'))  # 0
  • count(): Count the number of occurrences of a certain data in the current tuple.
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.count('bb'))  # 2
  • len(): count the number of data in the tuple.
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(len(tuple1))  # 4

Note: If the direct data in the tuple is modified, an error will be reported immediately

tuple1 = ('aa', 'bb', 'cc', 'bb')
tuple1[0] = 'aaa'

But if there is a list in the tuple, it is supported to modify the data in the list, so it is very important to consciously.

tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30)
print(tuple2[2])  # 访问到列表

# 结果:(10, 20, ['aaaaa', 'bb', 'cc'], 50, 30)
tuple2[2][0] = 'aaaaa'
print(tuple2)

Four. Summary

  • Define tuple
t1 = (10, 20, 30)

t2 = (10,)
  • Common methods of operation
    • index()
    • len ()

The content of this section is over, please pay attention, don’t get lost
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38454176/article/details/112172845