Python系統學習第七課
阿新 • • 發佈:2019-01-04
#list(列表)
- del刪除
a = [1,2,3,4,5,6]
del a[2]
print(a)
[1, 2, 4, 5, 6]
#使用加號連線兩個列表
a = [1,2,3,4]
b = [5,6,7,8]
c = a + b
print(c)
[1, 2, 3, 4, 5, 6, 7, 8]
#使用乘號操作列表
#相當於把n個列表接在一起
a = [1,2,3]
b = a * 3
print(b)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
#成員資格運算
a = [1,2,3,4]
b = 5
c = b in a
print(c)
print(b in a) #也可以用
False
False
#連結串列的遍歷
- for
- while
a = [1,2,3,4]
for i in a:
print(i)
1
2
3
4
#一般不用while訪問列表
a = [1,2,3,4,5]
length = len(a)
i = 0
while i < length:
print(a[i])
i += 1
1
2
3
4
5
#雙層列表迴圈
# a為巢狀列表,或者叫雙層列表吧
a = [["one", 1], ["two", 2], ["three", 3]]
for i,j in a:
print(i, "--", j)
one -- 1
two -- 2
three -- 3
#列表內涵:list content
- 通過list建立一個list b
a = ['1','2','3']
b = [i for i in a]
print(b)
['1', '2', '3']
a = ['1','2','3']
b = [i*10 for i in a]
print(b)
['1111111111', '2222222222', '3333333333']
a = [i for i in range(1,30)]
b = [i for i in a if i%2==0] #過濾掉原來列表中的元素,生成一個新的列表
print(b)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
aa = [i for i in range(1, 10)]
print(aa)
bb = [j for j in range(10, 20)]
print(bb)
cc = [m+n for m in aa for n in bb] # 兩個列表的雙重迴圈
print(cc)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
#關於列表的常用函式
- 求列表長度
- len()
- 求列表的最大值,最小值
- max(),min()
#將其他資料型別轉化為列表
a = "i love you!"
print(list(a))
print(a)
['i', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u', '!']
i love you!
#將range產生的資料轉化成列表
print(list(range(2,9)))
[2, 3, 4, 5, 6, 7, 8]