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

[Python example] list comprehensive application - random allocation office

編輯:Python

demand : There are three offices ,8 Teacher ,8 Four teachers were randomly assigned to 3 One office

Analysis steps :

1、 Prepare the data

  1. 1 -8 An old hand ---- List storage
  2. 3 One office --- List nested storage

2、 Assign teachers to the office --- Random allocation ( Random number module )

It's just putting the teacher's name on the office list ( Add the teacher's name to the list of companies )、

3、 Verify that the assignment was successful

Print office details , The number of people in each office and the corresponding teacher's name

Case implementation code :

import random
# 1. Prepare the data
teachers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
offices = [[], [], []]
# 2. Assign teachers to the office --- Take each teacher and put it on the office list ( Traverse the teacher data list )
for name in teachers:
# Method of appending data to the list : append extend insert ---- The final choice append() accord with
# xx[0]--- You cannot specify a specific subscript --- Using random number module
num = random.randint(0, 2) # Randomly get 0 1 2 Numbers
offices[num].append(name)
# print(offices) # Print multiple times to verify that the teachers assigned to each office are different
# In order to fit life better , Add an office number to each office sub list : 1 2 3
i = 1
# 3. Verify that the assignment was successful
for office in offices:
# Print the number of people in the office --- The number of sublist data len()
print(f' The office {i} The number of people who are {len(office)}, Teacher assignment is :')
# Print the teacher's name
# print() --- The number of names in each sub list is not necessarily -- Traversal sublist
for name in office:
print(name)
i += 1

Execution results : Because it's random , Here I will intercept the result pictures of two random assignments

List summary :

List format :[ data 1, data 2, data 3, ...]

Common operation methods :Index()、len()、append()、pop()、remove()

List nesting : You can also nest multiple lists in a list

List loop :while or for

The knowledge points involved above include random modules 、 List operation data function 、 Loop traversal, etc , After you've seen it, knock out the code of this case and practice more , Strengthen and consolidate the knowledge points of the list , It is suggested to consolidate the previous article from time to time python Basic course It is also necessary to write knowledge points .


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