列表 - 計數 - count回憶
上次研究了python文件運行時的系統參數
sys.argv
通過sys.argv就可以接收從命令行來的參數了
可以通過索引來獲得第n個參數
這就是索引(index)的作用
處理了可能出現的
IndexError
ValueError
列表(list)還有什么方法呢?
clist = list("oeasyo2zo3z")
clist
總共有3個
'o'
index
clist.index("o")
我們可以通過index方法
得到列表中
第1個"o"的位置
那如何 才能 得到
第2個、第3個"o"的位置呢?
first = clist.index("o")firstsecond = clist.index("o",first + 1)secondthird = clist.index("o",second + 1)
third
逐個往后
序號位置第0個下標0第1個下標5第2個下標8
還能繼續找嗎?
fourth = clist.index("o", third + 1)
如果此時
再從9開始
去查找"o"的索引
就找不到了
總共有3個"o"
有什么更快的方法嗎?
先統計一下有多少個'o'
clist = list("oeasyo2zo3z")
clist.count("o")
總共3個
這個count是什么意思呢?
help(list.count)
統計參數出現的次數
count 是 計數函數
len 也是
有什么區別嗎?
len(clist)
clist.count("o")
結果
lencount容器總長度指定列表項的 數量builtins的內置函數列表類對象的 方法列表 作為 參數列表對象 作為 主調對象
append 對于 count結果有影響嗎?
clist = list("oeasy")
clist.count("o")
clist.append("o")
clist.count("o")
append之后
count計數結果會變化
remove呢?
clist = list("oeasy")
clist.count("o")
clist.remove("o")
clist.count("o")
刪除 對 計數
也會有影響
問題是remove
每次都 從開始位置 刪
先刪 第1個"o"
我想讓他
先刪除最后一個"o"
怎么辦?
clist = list("oeasyo2z")
count = clist.count("o")
pos = 0
for num in range(count):
pos = clist.index("o", pos)
pos = pos + 1
print(pos)
先找到最后o的索引序號
位置找到了
第6個 列表項
其實 索引號 應該 是 5
clist = list("oeasyo2z")
count = clist.count("o")
i = 0
for num in range(count):
i = clist.index("o", i)
i = i + 1
i = i - 1
print(i)
這樣可以得到最后一個o的索引值
找到了 之后
怎么
刪除
呢?
我要刪除第5個列表項
remove方法沒有start參數
怎么辦??
找到了這個元素下標為6
就先替換了
然后再刪除
clist[5] = "sth special!"clist
clist.remove("sth special!")
clist
確實刪除成功
還有更快的辦法嗎?
clist = list("oeasyo2z")del clist[5]print(clist)
執行
確實可以
回憶del
del 是
keyword
a
a = 0adel a
a
以前是刪除 聲明過的變量
現在是 刪除 列表中 被索引的列表項
del clist[5]
除了 列表類 有 count方法之外
字符串也有count方法嗎?
s = "oeasyo2z"
s.count("o")
s.count("easy")
確實也有
查詢幫助手冊
help(str.count)
幫助手冊和列表的差不多
練習
板凳寬,扁擔長,板凳比扁擔寬,扁擔比板凳長,扁擔要綁在板凳上,板凳不讓扁擔綁在板凳上,扁擔偏要板凳讓扁擔綁在板凳上。
問
扁擔 出現次數多?
還是 板凳 出現次數多?
我們去總結一下
這次研究了 計數函數count
統計 列表中 某個列表項 出現次數
統計 某字符串 在 字符串中 出現的次數
count與len不同
count統計 列表項出現次數
len統計 列表的長度
count 這個詞怎么來的呢?
下次再說
藍橋->https://www.lanqiao.cn/courses/3584
github->https://github.com/overmind1980/oeasy-python-tutorial
gitee->https://gitee.com/overmind1980/oeasypython
特別聲明:以上內容(如有圖片或視頻亦包括在內)為自媒體平臺“網易號”用戶上傳并發布,本平臺僅提供信息存儲服務。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.