Python入門之列表

2021-10-02 15:25:45 字數 2765 閱讀 7184

python中的列表類似於c語言中的陣列,下面通過例項說明介紹幾種常用的使用方法。

1.空列表的建立

>>

> empty=

>>

>

print

(empty)

2.列表中元素的檢視

>>

> words=

["a"

,"b"

,"c"

]>>

>

print

(words[2]

)c>>

>

print

(words[3]

)traceback (most recent call last)

: file ""

, line 1,in

indexerror:

list index out of range

3.列表的修改

>>

> words=

["a"

,'b',1

,2,'3'

]>>

> words[0]

=0>>

>

print

(words)[0

,'b',1

,2,'3'

]

4.列表的運算

>>

> nums=[1

,2,3

,4,5

]>>

>

print

(nums+[6

,7])

[1,2

,3,4

,5,6

,7]>>

>

print

(nums-[1

])traceback (most recent call last)

: file ""

, line 1,in

typeerror: unsupported operand type

(s)for-:

'list'

and'list'

>>

>

print

(nums*2)

[1,2

,3,4

,5,1

,2,3

,4,5

]>>

>

print

(nums/2)

traceback (most recent call last)

: file ""

, line 1,in

typeerror: unsupported operand type

(s)for/:

'list'

and'int'

只能進行加乘,且不會改變原列表中的元素。

5.多列表的組合

>>

> words=[1

,2,3

,[4,

'a',

'b'],5

,6]>>

>

print

(words[1]

)2>>

>

print

(words[3]

[1])

a

6.列表的檢測

>>

> words=[1

,2,3

,[4,

'a',

'b'],5

,6]>>

>

print

('c'

in words)

false

>>

>

print

('d'

notin words)

true

>>

>

print

(not

'd'in words)

true

主要用於檢測某元素是否在該列表中

7.列表中元素的插入

>>

> nums=[1

,2,3

,4,5

]>>0)

>>

>

print

(nums)[1

,2,3

,4,5

,0]>>

> index=

4>>

> nums.insert(index,

"a")

>>

>

print

(nums)[1

,2,3

,4,'a',5

,0]

8.列表中某元素的位置

>>

> words=

['p'

,'y'

,'t'

,'h'

,'o'

,'n'

]>>

>

print

(words.index(

't')

)2

其他函式我就不一一舉例,如下:

len(list):獲取列表的長度

max(list):獲取列表中的最大值

min(list):獲取列表中的最小值

list.remove(x):刪除列表中的某個元素

list.count(x):獲取列表中某元素出現的次數

Python快速入門(五)之列表

列表 一 建立列表 可以用 來建立乙個列表,列表中的元素之間使用逗號分隔。示例 建立列表list hello 金融 理財 123 list hello 金融 理財 123 type list class list list hello 保險 理財 123 二 獲取元素 可以使用索引獲取列表中的元素,...

Python學習入門之列表(一)

列表是由一系列按特定順序排列的元素組成的,跟其他語言的陣列類似 names zr hc ws hj fz nums 1,2,3,9,4,5,8,7,6 可以直接使用print函式直接將陣列所有函式列印出來 print names 訪問列表元素,索引從0而不是從1開始,索引還可以使用負數,比如索引 1...

python入門之列表和元組

列表和元組是一組資料的集合,同乙個集合中的元素型別可以不一樣 1.1 列表的基本操作 索引操作 分片操作 序列相加 序列相乘等 例如 索引操作 x 1,adb 3,45 print x 1 輸出adb print x 1 輸出45 例如 分片操作 x abcdefg print x 1 2 prin...