我正在使用 click 創建一個命令列工具來執行一些資料預處理。到現在為止,我基本上已經在我的代碼中使用 click.option() 作為標志和一些 if 陳述句幸存下來,這樣我就可以選擇我想要的選項。但是,我正在努力尋找一種優雅的方式來解決我的下一個問題。因為我相信通用代碼結構不取決于我的目的,所以我會盡量保持通用,而不涉及主代碼的細節。
我有一個元素串列my_list,我想回圈并在每次迭代后應用一些非常長的代碼。但是,我希望這取決于一個標志(正如我所說,通過點擊)。一般結構是這樣的:
@click.option('--myflag', is_flag=True)
#just used click.option to point out that I use click but it is just a boolean
if myflag:
for i in my_list:
print('Function that depends on i')
print('Here goes the rest of the code')
else:
print('Function independent on i')
print('Here goes the rest of the code')
我的問題是我不想復制粘貼上述結構中其余代碼的兩倍(這是一個很長的代碼,很難集成到一個函式中)。有沒有辦法做到這一點?也就是說,有沒有辦法告訴python:“如果myflag==True,運行完整的代碼,同時回圈進入mylist。否則,只需轉到完整的代碼。所有這些都無需復制代碼。
編輯:我相信更具體一點實際上可能有用。
我所擁有的是:
mylist=['washington','la','houston']
if myflag:
for i in my_list:
train,test = full_data[full_data.city!=i],full_data[full_data.city==i]
print('CODE:Clean,tokenize,train,performance')
else:
def train_test_split2(df, frac=0.2):
# get random sample
test = df.sample(frac=frac, axis=0,random_state=123)
# get everything but the test sample
train = df.drop(index=test.index)
return train, test
train, test = train_test_split2(full_data[['tidy_tweet', 'classify']])
print('CODE: Clean,tokenize,train,performance')
full_data是一個包含文本和分類的 pandas 資料框。每當我設定my_flag=True時,我都會假裝訓練一些模型的代碼在離開某個城市作為測驗資料時測驗性能。因此,這個回圈讓我大致了解了我的模型在不同城市的表現(某種 GroupKfold 回圈)。
Under the second option, my_flag=False, there is a random test-train split and the training is only performed once.
It is the CODE part that I don't want to duplicate.
I hope this helps the previous intuition.
uj5u.com熱心網友回復:
“難以集成到功能中”是什么意思?如果函式是一個選項,只需使用以下代碼。
def rest_of_the_code(i):
...
if myflag:
for i in my_list:
print('Function that depends on i')
rest_of_the_code(i)
else:
print('Function independent on i')
rest_of_the_code(0)
否則,您可以執行以下操作:
if not myflag:
my_list = [0] # if you even need to initialize it, not sure where my_list comes from
for i in my_list:
print('Function that may depend on i')
print('Here goes the rest of the code')
編輯以回答您的說明:您可以使用迭代的串列。
mylist=['washington','la','houston']
list_of_dataframes = []
if myflag:
for i in my_list:
train,test = full_data[full_data.city!=i],full_data[full_data.city==i]
list_of_dataframes.append( (train, test) )
else:
train, test = train_test_split2(full_data[['tidy_tweet', 'classify']])
list_of_dataframes.append( (train, test) )
for train, test in list_of_dataframes:
print('CODE: Clean,tokenize,train,performance')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452305.html
