列表內建方法

2022-09-06 16:00:13 字數 2391 閱讀 2650

用來儲存多個愛好什麼的

hobby=['paly','sleep']

hobby_list = ['play', 'swimming', 'dancing','666']

print(1, hobby_list[-1])

hobby_list[-1] = '233'  # 索引修改

print(2, hobby_list[-1])

1 6662 233

hobby_list = ['play', 'swimming', 'dancing','666']

print(hobby_list[:])  

print(hobby_list[::-1])# 從右到左

['play', 'swimming', 'dancing', '666']

['666', 'dancing', 'swimming', 'play']

hobby_list = ['play', 'swimming', 'dancing','666']

print(len(hobby_list))

4

hobby_list = ['play', 'swimming', 'dancing', '666']

print('play' in hobby_list)  true

true

for hobby in hobby_list:  

print(hobby)

playswimmingdancing666

del hobby_list[-1]

print(hobby_list)

playswimmingdancing

['play', 'swimming', 'dancing', '666', 'dapao-->piao']

hobby_list = ['play', 'swimming', '666', 666, '666']

print(hobby_list.count('666')) #對列表內的某乙個元素計數

2

hobby_list = ['play', 'swimming', '666', 666, '666']

hobby_list.extend([1,2])

print(hobby_list)

['play', 'swimming', '666', 666, '666', 1, 2]

hobby_list.clear()

print(hobby_list)

hobby_list2 = hobby_list.copy()  # 複製列表

hobby_list = ['play', 'swimming', '666', 666, '666']

hobby_list.pop()

print(hobby_list)

['play', 'swimming', '666', 666]

print(hobby_list.index('play'))  # 索引

print(hobby_list.index('play', 2, 4))  # 索引2-4內有沒有該值

03

hobby_list = ['play', 'swimming', '666', 666, '666']

hobby_list.insert(0, '1')  # 插入

print(hobby_list)

['1', 'play', 'swimming', '666', 666, '666']

hobby_list = ['play', 'swimming', '666', 666, '666']

hobby_list.remove('1')  # 移除

print(hobby_list)

['play', '666', 666, '666']

hobby_list = ['play', 'swimming', '666', 666, '666']

hobby_list.reverse()

print(hobby_list)

['666', 666, '666', 'swimming', 'play']

hobby_list = ['play', 'swimming', '666', '666']

hobby_list.sort()

print(hobby_list)

['666', '666', 'play', 'swimming']

多個值有序

可變資料型別

列表內建方法

cmp 方法比較兩個列表的元素。以下是cmp 方法的語法 cmp list1,list2 引數 返回值如果元素是相同型別的,執行比較,並返回結果。如果元素是不同的型別,檢查,看看他們是否是數字 如果到達了列表中的乙個的結束,較長的列表是 大 如果耗盡列表和共享相同的資料,其結果是並列的,這意味著返回...

列表內建方法

目錄氣泡排序法 lt 1,2,3,4 print lt 1 lt 1 3 print lt 2 1,3,3,4 print lt 冒號左邊沒有左邊取到頭,右邊沒有則右邊取到頭 print lt 1 2 顧頭不顧尾,只列印索引號為1的元素 print lt 1 4 2 步長為2 1,3,3,4 3 3...

列表型別內建方法

1.用途 多個裝備 多個愛好 多門課程,甚至是多個女朋友 2.定義 內可以有多個任意型別的值,逗號分隔元素 my girl friend list jason tank sean my girl friend jason tank sean print f my girl friend my gir...