**:(列表索引)
mlist = [1, 2, 3, [3, "e", 4, 5], "a", "a", "abc", (5, 6, 7)]
print(mlist)
print(mlist[3:7])
print(mlist[3][1])
print(len(mlist))
mlist[2] = ["hi, python"]
print(mlist)
print(mlist[-3:-6])
print(mlist[-3:-6:-1])
print(mlist[-6:-3])
print(mlist[-6:-3:-1])
[1, 2, 3, [3, 'e', 4, 5], 'a', 'a', 'abc', (5, 6, 7)]
[[3, 'e', 4, 5], 'a', 'a', 'abc']
e[1, 2, ['hi, python'], [3, 'e', 4, 5], 'a', 'a', 'abc', (5, 6, 7)]
['a', 'a', [3, 'e', 4, 5]]
[['hi, python'], [3, 'e', 4, 5], 'a']
**:(列表拼接和重複)
mlist1 = ["a", "ab", 1, 12]
mlist2 = ["hi python", 4, 5]
print(mlist1 + mlist2)
print(mlist2 * 2)
print(mlist1 + ["excuse me!", "mr wang"])
['a', 'ab', 1, 12, 'hi python', 4, 5]
['hi python', 4, 5, 'hi python', 4, 5]
['a', 'ab', 1, 12, 'excuse me!', 'mr wang']
**:(增加元素)
mlist3 = [2, 3, 3, 3, 4, 6, 8, 10]
print(mlist3)
print(mlist3)
print(mlist3)
mlist3.extend([1, 3, 5, 7, 9])
print(mlist3)
mlist3.insert(2, "python")
print(mlist3)
print(mlist3.count(3))
[2, 3, 3, 3, 4, 6, 8, 10]
[2, 3, 3, 3, 4, 6, 8, 10, 1]
[2, 3, 3, 3, 4, 6, 8, 10, 1, [1, 3, 5, 7, 9]]
[2, 3, 3, 3, 4, 6, 8, 10, 1, [1, 3, 5, 7, 9], 1, 3, 5, 7, 9]
[2, 3, 'python', 3, 3, 4, 6, 8, 10, 1, [1, 3, 5, 7, 9], 1, 3, 5, 7, 9]
**:(刪除元素)
mlist4 = [2, 3, 3, 3, 4, 6, "python真有趣", 8, 10, "python", "hi"]
print("當前列表為:", mlist4)
print(mlist4.pop())
print(mlist4.pop())
print("當前列表為:", mlist4)
print(mlist4.pop())
print(mlist4.pop())
print("當前列表為:", mlist4)
print(mlist4.pop())
print(mlist4.pop())
print("當前列表為:", mlist4)
mlist5 = [2, 3, 3, 3, 4, 6, "python真有趣", 8, 10, "python", "hi"]
mlist5.remove("python")
print("mlist5----",mlist5)
當前列表為: [2, 3, 3, 3, 4, 6, 'python真有趣', 8, 10, 'python', 'hi']
hipython
當前列表為: [2, 3, 3, 3, 4, 6, 'python真有趣', 8, 10]
當前列表為: [2, 3, 3, 3, 4, 6, 'python真有趣']
python真有趣
當前列表為: [2, 3, 3, 3, 4]
mlist5---- [2, 3, 3, 3, 4, 6, 'python真有趣', 8, 10, 'hi']
**:(列表的反轉)
mlist5 = [2, 3, 3, 3, 4, 6, "python真有趣", 8, 10, "python", "hi"]
print("原始列表:", mlist5)
mlist5.reverse()
print("反轉後的列表:", mlist5)
原始列表: [2, 3, 3, 3, 4, 6, 'python真有趣', 8, 10, 'python', 'hi']
反轉後的列表: ['hi', 'python', 10, 8, 'python真有趣', 6, 4, 3, 3, 3, 2]
**:(列表排序)
mlist6 = ["e","a","g","s"]
print("原始列表:", mlist6)
mlist6.sort()
print("排序後的列表:", mlist6)
mlist7 = [7, 17, 1, 4, 0, 55, 8, 23, 333]
print("原始列表:", mlist7)
mlist7.sort()
print("排序後的列表:", mlist7)
原始列表: ['e', 'a', 'g', 's']
排序後的列表: ['a', 'e', 'g', 's']
原始列表: [7, 17, 1, 4, 0, 55, 8, 23, 333]
排序後的列表: [0, 1, 4, 7, 8, 17, 23, 55, 333]
python整數和列表 列表和整數Python
假設實際縮排如下 specialnum 10 def number move move number for elements in range len move number if specialnum move number 1 x move number.index specialnum y ...
Python 列表的使用
需要儲存多個不同的變數 定義列表 儲存的資料型別可以不同 但盡可能儲存相同的資料型別 l 123,456,789,hello 3.14 定義乙個列表 name list 張三 李四 王五 趙六 print name list 0 print name list 1 print name list 2...
Python列表的使用
2 列表的常用方法 a b 1,a 34,1,2 print a,type a print b,type b 1,a 34,1,2 a 1,2 b 2,3 print a b print a 3 輸出 1,2,2,3 1,2,1,2,1,2 a 1,2 b 2,3,1,2 c true,2,1,2 ...