列表是最常用的Python資料型別之一,也是五大金剛中操作方式最多的一個資料型別。
本文將從八個角度粉碎性擊破這一難點。
pyhon中list中不需要具有相同的型別,用[ ]表示一個列表
主要有兩種建立方法:用[]括住直接建立,或者用關鍵詞list()建立
a = [1,2,3,4]
b= ["zhangsan","lisi","wangwu"]
c = [1,2,"zhangsan",(1,2)] #但元組(1,2)將視為一個元素
>>[1, 2, 3, 4]
>>['zhangsan', 'lisi', 'wangwu']
>>[1, 2, 'zhangsan', (1, 2)]
d = list("hello")
f = list(range(4))
g = list((1,2,3,4))
>>['h', 'e', 'l', 'l', 'o']
>>[0, 1, 2, 3]
>>[1, 2, 3, 4]
cat = []
cat.append("tuantuan")
cat.append("yuanyuan")
print(cat)
>>['tuantuan', 'yuanyuan']
cat.insert(1,"daju")
cat.insert(8,"maoye") #如果指定位置超出列表範圍,會自動加到最後一位
print(cat)
['tuantuan', 'daju', 'yuanyuan', 'maoye']
dog = ["haha","beibei"]
cat.extend(dog) #將dog加入到cat裡
print(cat)
>>['tuantuan', 'daju', 'yuanyuan', 'maoye', 'haha', 'beibei']
print(cat)
del cat[-1]
print(cat)
['tuantuan', 'daju', 'yuanyuan', 'maoye', 'haha', 'beibei']
['tuantuan', 'daju', 'yuanyuan', 'maoye', 'haha']
l = [1,2,3,4,5]
print(l.pop())
print(l.pop(0))
print(l)
>>5
>1
>>[2, 3, 4]
print(l)
if 2 in l:
l.remove(2)
print(l)
>>[2, 3, 4]
>>[3, 4]
p = [1,2,3,4,5]
p[0] = 9
print(p)
>>[9, 2, 3, 4, 5]
u = [3,8,7,5,2]
print("第二個元素是: ",u[1])
print("元素2的索引值是:",u.index(2))
print("列表長度是:",len(u))
>>第二個元素是: 8
>>元素2的索引值是: 4
>>列表長度是: 5
name = ["崔","張","李","王"]
for n in name:
print(n ,end="")
print()
for index,n in enumerate(name):
print(f"no.{index} is {n}")
>>崔張李王
>>no.0 is 崔
>>no.1 is 張
>>no.2 is 李
>>no.3 is 王
print(name*2)
>>['崔', '張', '李', '王', '崔', '張', '李', '王']
print(name+[1,2,3])
>>['崔', '張', '李', '王', 1, 2, 3]
#reverse()
score = [67,84,78,56,98]
score.reverse()
print(score)
>>[98, 56, 78, 84, 67]
#sort()
score.sort()
>>[56, 67, 78, 84, 98]
#sorted()
score = [67,84,78,56,98]
print(sorted(score))
print(score)
>>[56, 67, 78, 84, 98]
>>[67, 84, 78, 56, 98]
score = [67,84,78,56,98]
print(max(score))
print(min(score))
>>98
>>56
score = [67,84,78,56,98]
print(score[0:4:2])
>>[67, 78]
nums = list(range(10))
print(nums)
nums_2 = [n+2 for n in nums]
print(nums_2)
nums_3 = [n for n in nums if n%2==0]
print(nums_3)
>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>[0, 2, 4, 6, 8]
nums = list(range(10))
nums_4 = nums[:]
print(nums_4)
>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
創作不易,如果覺得有幫助的話希望可以點個贊,十分感謝!