zoukankan      html  css  js  c++  java
  • (一)Python入门-3序列:05列表-元素的访问-元素出现次数统计-成员资格判断

    一:通过索引直接访问元素

      可以通过索引直接访问元素。索引的区间在[0, 列表长度-1]这个范围。超过这个范围则 会抛出异常。

     1 >>> a = [10,20,30,40,50,20,30]
     2       
     3 >>> a[2]
     4       
     5 30
     6 >>> a[10]
     7       
     8 Traceback (most recent call last):
     9   File "<pyshell#218>", line 1, in <module>
    10     a[10]
    11 IndexError: list index out of range

    二:index()获取指定元素在列表中首次出现的索引

      index()可以获取指定元素首次出现的索引位置。语法是: index(value,[start,[end]])。其中, start 和end指定了搜索的范围。

     1 >>> a = [10,20,30,40,50,20,30]
     2       
     3 >>> a.index(20)
     4       
     5 1
     6 >>> a.index(20,3)
     7       
     8 5
     9 >>> a.index(20,3)   #从索引位置3开始往后搜索的第一个20
    10       
    11 5
    12 >>> a.index(30,5,7)  #从索引位置5到7这个区间,第一次出现30元素的位置
    13       
    14 6

    三:count()获得指定元素在列表中出现的次数

      count()可以返回指定元素在列表中出现的次数。

    1 >>> a = [10,20,30,40,50,20,30,20]
    2       
    3 >>> a.count(20)
    4       
    5 3

    四:len()返回列表长度

      len()返回列表长度,即列表中包含元素的个数。

    1 >>> a = [10,20,30,40,50,20,30,20]
    2       
    3 >>> len(a)
    4       
    5 8

    五:成员资格判断

      判断列表中是否存在指定的元素,我们可以使用 count()方法,返回0则表示不存在,返回 大于 0 则表示存在。但是,一般我们会使用更加简洁的 in 关键字来判断,直接返回 True 或False。

     1 >>> a = [10,20,30,40,50,20,30,20]
     2       
     3 >>> 20 in a
     4       
     5 True
     6 >>> 100 in a
     7       
     8 False
     9 >>> 100 not in a
    10       
    11 True
  • 相关阅读:
    [LuoguP2161] 会场预约
    [LuoguP1198] 最大数
    [LuoguP1484] 种树
    [LuoguP1801] 黑匣子
    [LuoguP1196]银河英雄传说
    [LuoguP1345] 奶牛的电信Telecowmunication
    [LuoguP1119]灾后重建
    【笔记】一元函数微分学
    【复习】Listening and Reading Comprehension
    【笔记】一元函数的不定积分
  • 原文地址:https://www.cnblogs.com/jack-zh/p/10816467.html
Copyright © 2011-2022 走看看