五、列表的操作

列表是python中常見的基礎(chǔ)數(shù)據(jù)類型,下面簡單介紹列表的常見操作

  • 創(chuàng)建一個列表
list = [1, "hello", 3.0, True]
print(list)

輸入結(jié)果:
[1, 'hello', 3.0, True]

  • 增加一個元素
list = [1, "hello", 3.0, True]
print(list)

# 尾部插入一個元素
list.append("world")
print(list)

# 中間插入一個元素
list.insert(1, "name")
print(list)
顯示結(jié)果
[1, 'hello', 3.0, True]
[1, 'hello', 3.0, True, 'world']
[1, 'name', 'hello', 3.0, True, 'world']
  • 刪除元素
list = [1, 'name', 'hello', 3.0, True, 'world']
list.pop(1)
print(list)
list.remove("hello")
print(list)

顯示結(jié)果
[1, 'hello', 3.0, True, 'world']
[1, 3.0, True, 'world']
  • 修改元素
list = [1, "hello", 3.0, True]
list[2] = "name"
print(list)

顯示結(jié)果
[1, 'hello', 'name', True]
  • 查詢元素
list = [1, "hello", 3.0, True]
print(list[2])

顯示結(jié)果
3.0
  • 常用函數(shù)
# -*- coding:utf-8 -*-


# 列表長度
list = [1, "hello", 3.0, True]
l = len(list)
print("長度%d" % l)

list = [1, 2, 3, 5, 7, 0, 3, 4, 5]

# 獲取最大、最小值 不支持不同類型比較
print("max:%d" % max(list))
print("min:%d" % min(list))
# 遍歷5 在數(shù)組的次數(shù)
print("count:%d" % list.count(5))

print("列表中第一個5的索引%d" % list.index(5))
print("列表中第二個5的索引%d" % list.index(5, list.index(5) + 1))

# 反轉(zhuǎn)
list.reverse()
print(list)

# 排序
list.sort()
print(list)
顯示結(jié)果

長度4
max:7
min:0
count:2
列表中第一個5的索引3
列表中第二個5的索引8
[5, 4, 3, 0, 7, 5, 3, 2, 1]
[0, 1, 2, 3, 3, 4, 5, 5, 7]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時實驗課主要內(nèi)容 【Python簡介】: Python 是一個...
    _小老虎_閱讀 6,338評論 0 10
  • 〇、前言 本文共108張圖,流量黨請慎重! 歷時1個半月,我把自己學(xué)習(xí)Python基礎(chǔ)知識的框架詳細(xì)梳理了一遍。 ...
    Raxxie閱讀 19,589評論 17 410
  • 剛才有人敲門,我打開門一看,一個送外賣的小伙子,拎了很多蒸好的大閘蟹站在門外? 我說:“你一定是弄錯了,我沒叫外賣...
    幸福的眼淚_52da閱讀 194評論 0 1
  • 時尚是一種生活方式,更是一種發(fā)自內(nèi)心的、積極正面的生活態(tài)度。 時尚是什么? 有人說,時尚是一種風(fēng)格;有人說,時尚是...
    比藍(lán)秀閱讀 6,678評論 6 21
  • 我從2017年9月開始接觸青椒,因為第一次的相遇,讓我對它充滿了期待。還記得開學(xué)典禮時好多北師大的教授一個...
    陜縣306王玉平閱讀 233評論 0 0

友情鏈接更多精彩內(nèi)容