# Python與資料分析 HW2 筆記
## list comprehension
[想要輸出的形式或i的函數 for i in 想遍尋的位置 (if 條件)]
## isinstance(變數, 型態) 判斷型態
isinstance(x, bool)
若變數x是bool就會輸出True
其他型態亦可
## 質數
可以從2判斷到int(根號a)+1(因為用int會無條件捨去)
是否餘數0
但1 2會有問題,可以另外獨立寫出來
如果要蒐集某個區段的質數
可以看該數被2~int(根號a) +1整除的次數
(如果餘數0就counter +1)
如果0次就是質數
## 將母音字母大小寫互換
x.swapcase() 可以將字串x大小寫互換
只要改母音就好,可以用for迴圈遍尋字串x[i]
先建立空字串
如果x[i]是母音大小寫,就x[i].swapcase並迭加上該空字串
如果不是的話,x[i]直接迭加上去
Expected inputs:a string x
Expected outputs:a string
```
l = len(x)
ans = ''
for i in range(l):
if x[i] in 'aeiouAEIOU':
add = x[i].swapcase()
ans = ans + add
else:
ans = ans + x[i]
return ans
```
## 找list的中位數
先排序sorted(),依照中位數定義
奇數個就找中間的(l+1)/2
偶數個就找中間兩個的一半{[f(l/2)+f[(l/2)+1]}/2
*可否不要sort?
## 找list裡面最大值的index(可能超過一個)
創造空list 指定一個變數a放入最小值(如-1) 一個紀錄
遍尋list元素,若比a大就取代a,並將index更新進去空list
若等於a就把index append入list
## 找眾數
先用for迴圈建立一個dictionary包裝 數字:出現的次數
再用list.value列出所有value的部分
找出這裡面數字最大的數
再回去看dictionary哪些key的value是此數
Expected inputs:a list x
Expected outputs:an integer or a list of integers
```
diction = {i:0 for i in x}
for i in x:
diction[i] = diction[i] +1
dictionval = list(diction.values())
dictionkey = list(diction.keys())
maxfornow = -1
indexfornow = []
for i in range(0, len(dictionval)):
if dictionval[i] > maxfornow:
maxfornow = dictionval[i]
ans = [i for i in dictionkey if diction[i] == maxfornow]
if len(ans) == 1:
return ans[0]
else:
return ans
```
###### tags: `python` `資料分析`