def addTest(x, y): #兩個參數
z = x+y
return z
x, y = 5, 10
print(“普通方法:”, addTest(x, y))
lst = [5, 10] #長度2, 兩個元素,
#長度同參數個數
#tp = 5,10 也可以
print(“使用*list:”, addTest(*lst))
dic = {“x”: 5, “y”: 10} #兩個key,兩個value
#dic = dict(x=5, y=10)
# 不同寫法一樣意思
print(“字典:”, dic)
“””
key: x,y必須跟addTest的參數一模一樣
不能換成p,q,不然會出現
TypeError: addTest() got an unexpected keyword argument ‘p’
“””
print(“使用**dict:”, addTest(**dic))
print(“使用*dict:”, addTest(*dic))
# 變成key的相加

#使用*list

#使用**dict實例:
import numpy as np
time1 = np.linspace(0,0.5,3)
#避免變數名稱取名為time,
#以免用到import time的time模組時撞名
dicIn = {
“time1”: time1,
“gain” : 32767,
“delay”: 1e-6
}
def exportDict(time1,gain,delay):
dic = {}
dic[“time”] = time1
dic[“gain”] = np.ones(time1.shape)*gain
dic[“delay”] = np.ones(time1.shape)*delay
#time1.shape=(3,),type=tuple
return dic
print(exportDict(**dicIn))

解包與打包運算子:

**dict解包:
dict 的 Key 要與參數的名稱一樣,
而且不可多 不可少
一個*,兩種解讀
1. 打包第一個(不定長度)參數:

“””其實不一定要第一個參數
惟定義在「*參數」前面的
參數皆不可省略,而定義在「*參數」後面的
參數只能為指名參數或 **kwargs”””
參數皆不可省略,而定義在「*參數」後面的
參數只能為指名參數或 **kwargs”””
2. 將長度同參數個數的list
解包到函式(*list, **dict):

*list: list長度必須跟參數個數相同
**dict:
dict 的 Key 要與參數的名稱一樣,
而且不可多 不可少
(跟list長度同參數個數一樣意思)
*dict: 解包dict的keys,一般不會這樣用
解包與打包運算子
(**最後一個參數,當作dict變數):

不定長度的選擇性參數:

前面講的
*第一個參數,
也是不定長度參數
但是該不定長度參數是
必要輸入,非選擇性
輸入的參數視為tuple
**最後一個選擇性參數:

或如下:

*args **kwargs

*args

*args


**kwargs

範例:

![Python TQC考題604 眾數, cnt[L.index(n)]+=1, L[cnt.index(max(cnt))], if L.count(n)>maxcnt: Python TQC考題604 眾數, cnt[L.index(n)]+=1, L[cnt.index(max(cnt))], if L.count(n)>maxcnt:](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2022/04/20220430181911_73.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

![Python TQC考題810 最大值與最小值之差,L=[eval(i) for i in s.split()] Python TQC考題810 最大值與最小值之差,L=[eval(i) for i in s.split()]](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2022/05/20220507094526_36.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



![Python: 如何求整個 pandas.DataFrame 中的最大值? pandas.DataFrame .max().max() ; 如何求最大值的index, columns? numpy.where(condition, [x, y, ]/) ; condition為一 bool_mask Python: 如何求整個 pandas.DataFrame 中的最大值? pandas.DataFrame .max().max() ; 如何求最大值的index, columns? numpy.where(condition, [x, y, ]/) ; condition為一 bool_mask](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2023/04/20230418154049_50.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

![Python:如何用pandas.concat() 合併兩個DataFrame並重置index? pd.concat([df1, df2]) .reset_index(drop=True) ; pd.concat([df1, df2], ignore_index=True) Python:如何用pandas.concat() 合併兩個DataFrame並重置index? pd.concat([df1, df2]) .reset_index(drop=True) ; pd.concat([df1, df2], ignore_index=True)](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2023/03/20230311123232_5.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

近期留言