2

## 【python入門教室】(7) python 的列表生成式語法介紹

python是一門精簡的語言，

「切片」(slice)與「列表生成式」(List Comprehensions)

，為運用一個列表生出另一個列表的語法

``````新列表 = [something for x in 舊列表(或可迭代物件)]
``````

``````新列表 = []
for x in 舊列表(或可迭代物件):
新列表.append(something)
``````

``````新列表 = [something for x in 舊列表(或可迭代物件) if 條件判斷句]
``````

# 看看列表生成式的各種應用

## 生成1~10的平方數

``````>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
``````

## 將字串轉為字元陣列

``````>>> s="Hello"
>>> [c for c in s] #亦可直接寫 list(s)
['H', 'e', 'l', 'l', 'o']
``````

## 雙for迴圈生成全排列

``````>>> [m + n for m in 'abc' for n in '123']
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
``````

## 取出列表中的偶數

``````>>> L=[18, 73, -24, 6, 34, -87, -17, -98, -53, 16]
>>> [x for x in L if x%2==0]
[18, -24, 6, 34, -98, 16]
``````

## 取出列表中的負數

``````>>> [x for x in L if x<0]
[-24, -87, -17, -98, -53]
``````

## 取出列表中的字串型態

(註: 內建函數isinstance(x, type)可以判斷前者是否為後者的變數型態)

``````>>> M = ["Horse","Tiger",25,6.2,"Tomato"]
>>> [x for x in M if isinstance(x, str)]
['Horse', 'Tiger', 'Tomato']
``````

# 範例一: 救救我的期末分數啊

``````scores = [20,30,50,60,25,70]
``````

## 不用列表生成式怎麼解

``````new_scores = []
``````

``````adjust = 100 - max(scores)
``````

``````scores = [20,30,50,60,25,70]
new_scores = []
for s in scores:
print(new_scores)
``````

## 列表生成式怎麼解

``````scores = [20,30,50,60,25,70]
new_scores = [s+ 100 - max(scores) for s in scores]
``````

# 範例二: 各位數字和

6是3的倍數，所以123也是3的倍數。

``````def sumOfDigit(num):
pass
``````

## 解法一: 單純把輸入當作數字操作

``````123 % 10 = 3
123 // 10 = 12
12 % 10 = 2
12 //10 = 1
1 % 10 = 1
1 // 10 =0
``````

``````def sumOfDigit(num):
ans=0
while num>0:
ans+=num%10
num//=10
return ans
``````

## 解法二: 把輸入當作字串來處理

``````def sumOfDigit(num):
return sum([int(c) for c in str(num)])
``````

``````print(sumOfDigit(120)) #3
print(sumOfDigit(35)) #8
print(sumOfDigit(261)) #9
print(sumOfDigit(999)) #27
``````

# 切片v.s. 列表生成式

``````newArr = L[起始位置(包含) : 結束位置(不包含): 步長]
``````

range()函數的基礎語法為:

``````range(起始位置(包含), 結束位置(不包含), 步長)
``````

``````新列表 = [something for x in 舊列表(或可迭代物件，常常使用range)]
``````

`range(4,21,3)` 表示數字範圍 `4,7,10,13,16,19`
`L[4:21:3]` 則表示切片的列表 `[L[4], L[7], L[10], L[13], L[16], L[19]]`
`[L[i] for i in range(4,21,3)]` 亦可以表示`[L[4], L[7], L[10], L[13], L[16], L[19]]`

# 課後練習

1. 7kyu- Sum of a sequence -將範圍內的數字加總，大家可以想想怎麼寫較簡單

## 2. 韓信的千軍萬馬

``````def soldiers(m, n):
return #這邊寫你要回傳的列表
``````

``````輸入: m = 20, n=200

``````

### 1 則留言

1
Pondudu
iT邦新手 5 級 ‧ 2020-04-17 15:29:11

``````def soldiers(m, n):
return [x for x in range(m,n) if x%3 == 2 and x%5 == 3 and x%7 == 2]

print(soldiers(20,200))  #[23,128]
``````

``````L = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"
N = L.split(",")
print([N[i] for i in range(0,14,3)])
``````

Pondudu iT邦新手 5 級 ‧ 2020-04-17 15:48:19 檢舉

``````def sequence_sum(begin_number, end_number, step):
return sum([i for i in range(begin_number, end_number+1, step)])
``````

``````def soldiers(m, n):
return [x for x in range(m+1,n) if x%3 == 2 and x%5 == 3 and x%7 == 2]
``````

``````nums = [str(i) for i in range(1,14,3)]
print(nums)
``````

Pondudu iT邦新手 5 級 ‧ 2020-04-17 16:26:46 檢舉

``````#1
L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
newList = []
for i in range(0,14,3):
newList.append(L[i])
print(newList)

#2
newList = []
for i in range(1,15,3):
newList += [i]
print(newList)

#3
L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(L[0:14:3])  #切片語法

#4
newlist = [i for i in range(1,15,3)]  #列表生成語法
print(newlist)

#5
L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
newlist = [L[i] for i in range(0,14,3)]  #列表生成語法
print(newlist)
``````

``````for i in range(1,15,3):
n = list(str(i))
print(n)
``````

``````for i in range(1,15,3):
n = list(str(i))
print(str(i), list(str(i)))
print(n)
``````

``````>>> list("123")
['1', '2', '3']
``````

Pondudu iT邦新手 5 級 ‧ 2020-04-18 08:14:38 檢舉

``````n = [str(i) for i in range(1,15,3)]
``````

``````for i in range(1,15,3):
n = list(str(i))
``````

• str(數字)可以將數字保留原本的樣字轉成字串
• list(字串)會把字串轉換成一個一個的字元
• 把str(i)放在列表生成式裡並沒有把字串轉換成列表的動作，它就是把字串放在列表裡面

Pondudu iT邦新手 5 級 ‧ 2020-04-18 17:40:38 檢舉