列表(list)是Python中最基本的、最常用的数据结构(相当于C语言中的数组,与C语言不同的是:列表可以存储任意数据类型的数据)。 列表中的每一个元素分配一个索引号,且索引的下标是从0开始。

一、定义

  例如: lt = [1,2.3,True,'lala']

二、特性
  service = ['ssh','http','ftp']
  1)索引 

     service[0]        ## 显示第一个元素ssh
  2)切片    

     service[::-1]     ## 列表翻转
    service[1:]       ## 显示除了第一个的字符串
    service[:-1]      ## 显示除了最后一个字符串
  3)重复    

     service*3          ## 显示三遍
  4)连接    

     service + ['a','b']

  5)成员操作符    

     print 'firewalld' in service
  6)for循环遍历:每次从列表重取出一个字符串
    for se in service:
       print se,
三、列表中的嵌套
  service = [['http', 80], ['ssh', 22], ['ftp', 21]]
  注意:性质与列表相同
四、列表的增加
  1)+ :拼接
    Python中的数据结构 --- 列表(list)
  2)append(追加):追加一个元素到列表中(一般默认为追加在列表的末尾)
    Python中的数据结构 --- 列表(list)
  3)extend(拉伸):追加多个元素到列表中
    Python中的数据结构 --- 列表(list)
  4)insret:插入到固定的位置
    Python中的数据结构 --- 列表(list)
五、列表的删除
  1)pop:如果pop()不传递值的时候,默认弹出最后一个元素
   print service.pop()     ## 弹出最后一个元素
   print service.pop(1)    ## 弹出第二个元素
    Python中的数据结构 --- 列表(list)

  2)remove:删除指定的元素
   Python中的数据结构 --- 列表(list)

  3)del 关键字:从内存中删除列表
   Python中的数据结构 --- 列表(list)
六、列表的修改
  1)通过索引重新赋值
   Python中的数据结构 --- 列表(list)
  2)通过切片修改内容
   Python中的数据结构 --- 列表(list)
七、列表的查看

  1)count:查看列表中元素出现的次数
   Python中的数据结构 --- 列表(list)
  2)index:查看指定元素的索引值
   Python中的数据结构 --- 列表(list)
八、列表的排序:(正常情况下是按照ascll码的大小进行排序)
  1)使用sort()函数,实现正序排序

   Python中的数据结构 --- 列表(list)
  2)逆序排序
   Python中的数据结构 --- 列表(list)
  3)print sorted(service)    ##临时对列表元素进行排序
    Python中的数据结构 --- 列表(list)
  4)对字符串不区分大小写地排序
   service.sort(key=str.lower)  # 把大写当作小写进行排序
   service.sort(key=str.upper)  # 把小写当大写来进行排序

练习1:随即生成1-10的字符
import random
li = list(range(10))      ## 生成有序的0-9
print li

random.shuffle(li)        ## 生成无序的0-9数字
print li

相关文章:

  • 2018-10-31
  • 2022-12-23
  • 2021-12-30
  • 2021-11-25
  • 2021-07-05
  • 2022-12-23
  • 2022-01-29
  • 2022-12-23
猜你喜欢
  • 2021-06-28
  • 2021-12-05
  • 2021-05-25
  • 2022-12-23
  • 2021-12-24
  • 2021-10-17
相关资源
相似解决方案