zoukankan      html  css  js  c++  java
  • Python列表

    列表解决 多个变量命名的困难问题。

    列表类型  

    1. 采用相同数据类型的列表  testList=[1,2,3,4]   testList=['a','b']

    2. 采用不同数据类型的列表  testList=[1,'a',2,'b']  其实列表中的数据的类型可以是任意的。

    打印列表

    liStu=['Ding','Tao','Yan','Liu']

    print(liStu[0])

    print(liStu[1])

    print(liStu[2])

    print(liStu[3])

    列表的循环

    1.for

    nameList=['Ding','Yan','Tao','Liu']
    for name in nameList:
        print(name)
    

    2. while

    nameList=['Ding','Yan','Tao','Liu']
    length=len(nameList)
    i=0
    while i<length:
        print(nameList[i])
        i+=1
    

    列表常见操作

    1> 增加元素 (append、insert、extend)

    append(obj) 在列表末尾新增元素。

    insert(index,obj)在index位置,插入obj。

    extend(obj) 合并两个列表。

    2> 修改元素

    直接使用索引下标来修改

    liName=['Ding','Yan','Tao','Liu']

    liName[1]='Bei'

    3> 查找元素  (in、not in、index、count)

    4> 删除元素 (del、remove、pop)

    5> 排序(sort、reverse)

    列表嵌套

    schoolNames = [['北京大学','清华大学'],
                        ['南开大学','天津大学','天津师范大学'],
                        ['山东大学','中国海洋大学']]


     1 一个学校,有3个办公室,现在有8位老师等待工位的分配,请编写程序,完成随机的分配
     2 
     3 #encoding=utf-8
     4 
     5 import random
     6 
     7 # 定义一个列表用来保存3个办公室
     8 offices = [[],[],[]]
     9 
    10 # 定义一个列表用来存储8位老师的名字
    11 names = ['A','B','C','D','E','F','G','H']
    12 
    13 i = 0
    14 for name in names:
    15     index = random.randint(0,2)    
    16     offices[index].append(name)
    17 
    18 i = 1
    19 for tempNames in offices:
    20     print('办公室%d的人数为:%d'%(i,len(tempNames)))
    21     i+=1
    22     for name in tempNames:
    23         print("%s"%name,end='')
    24     print("
    ")
    25     print("-"*20)
    View Code
     
  • 相关阅读:
    Python学习第75天(js历史和引入,模块复习)
    Python学习第74天(抽屉习题笔记)
    Python学习第73天(shelve模块、习题练习)
    Js查漏补缺02-各种数据类型
    Js查漏补缺01-js学习笔记
    开篇
    小小python欢乐多
    阅读笔记09 个人对于三年来软件工程的一点心得
    14周周博客
    软件杯第二阶段
  • 原文地址:https://www.cnblogs.com/PythonInMyLife/p/6919605.html
Copyright © 2011-2022 走看看