Python 列表基礎

2021-10-09 06:36:28 字數 2802 閱讀 5544

所有可迭代型別都支援:

>>

>

len(

'abc')3

>>

>

len([1

,2,3

])3>>

>

len([1

,2,[

1,2,

3]])

3

>>

> list_ =[1

,2,3

]>>

'a')[1

,2,3

,'a'

]>>

['a'

,'b'

,'c'])

# 這裡前後是同乙個變數,應該包括前面的 'a',感謝大佬指正[1

,2,3

,'a',[

'a',

'b',

'c']

]# l.extend(iterable) -> none

>>

> list_.extend(

['a'

,'b'

,'c'])

[1,2

,3,'a'

,'b'

,'c'

]>>

> list_.extend(1)

typeerror:

'int'

object

isnot iterable

pop

# l.pop([index]) -> item

# -- remove and return item at index,移除並返回對應索引的物件,預設索引值為 -1,即最後乙個

>>

> list_ =[1

,2,3

]>>

> list_.pop()3

>>

> list_[1

,2]>>

> list_.pop(2)

indexerror: pop index out of range

>>

> list_.pop(0)

1>>

> list_[2

]

remove

# l.remove(value) -> none

# -- remove first occurence of value,移除等於這個值的第乙個元素

# raises valueerror if the value is not present

>>

> list_ =

['a'

,'b'

,'c'

]>>

> list_.remove(

'a')

['b'

,'c'

]# value specified

>>

false)[

'b',

'c',

false

]>>

> list_.remove(0)

['b'

,'c'

]# error

>>

> list_.remove(

'k')

valueerror:

list

.remove(x)

: x not

inlist

clear

# l.clear() -> none

# 移除所有物件

>>

> list_ =[1

,2,3

]>>

> list_.clear(

)>>

> list_

loa

ding

..

.loading...

loadin

g...

# l.sort(key=none, reverse=false) -> none

>>

> nums =[4

,2,5

,1,3

]>>

> nums.sort(

)# 預設公升序[1

,2,3

,4,5

]>>

> nums.sort(reverse=

true)[

5,4,

3,2,

1]

>>

> list_ =[1

,3,4

]>>

> list_.reverse()[

4,3,

1]

# l.index(object) -> int

# 返回物件的索引

>>

> list_ =[1

,3,4

]>>

> list_.index(3)

1

# l.count(object) -> int

# 返回目標計數物件在序列中的個數

>>

> list_ =[1

,1,[

1,1,

1,1]

]>>

> list_.count(1)

2>>

> list_.count([1

,1,1

,1])

1

Python基礎 列表

list name index 修改元素 索引並修改元素 永久排序 cars.sort 逆序cars.sort reverse true 臨時排序 sorted cars 逆序sorted cars,reverse true 永久反轉列表元素 cars.reverse 確定列表長度 len cars...

Python基礎 列表

遍歷中的bug 姓名管理系統 遍歷 取出索引得資料,索引的順序是從0開始的 list1 1,test 1.23 print list1 1 list2 1,a 1.2 2,b 3.4 3,c 5.6 print list2 2 2 索引同時也可以直接在反向執行,最左邊是 1 print list2 ...

python基礎 列表

numer list 1,2,3,4 用下標取得列表中的單個值 print numer list 0 numer list 1,2,3,4 負數下標 print numer list 1 result 4numer list 1,2,3,4 利用切片取得子列表 print numer list 0 ...