我在串列上有一個 for 回圈,f如下所示,我有一個條件陳述句,其中串列的第一個物件不滿足,但第二個和第三個物件滿足。出于某種原因,條件沒有回傳預期的結果,我不明白為什么會這樣?
最小作業示例
# containers
absolute_path_list = []
f = [ 'Documents/projects/packout_model/.venv/lib/python3.9/site-packages/numpy/core/tests/data/file1.csv',
'Documents/projects/packout_model/data/03-06-2022/csv_store/file2.csv',
'/Documents/projects/packout_model/data/03-06-2022/csv_store/file3.csv']
# loop over f to find files that meet our condition
for file in f:
if (file.find('csv_store') and file.find('03-06-2022')) and (file.find('packout_model') and file.endswith("csv")): # error here
absolute_path_list.append(file)
print(absolute_path_list) # print list of str objects that met condition
正在生成的輸出
[ 'Documents/projects/packout_model/.venv/lib/python3.9/site-packages/numpy/core/tests/data/file1.csv',
'Documents/projects/packout_model/data/03-06-2022/csv_store/file2.csv',
'/Documents/projects/packout_model/data/03-06-2022/csv_store/file3.csv']
期望的輸出
['Documents/projects/packout_model/data/03-06-2022/csv_store/file2.csv',
'/Documents/projects/packout_model/data/03-06-2022/csv_store/file3.csv']
編輯:
解決答案的解決方案
使用提供的答案,我設法撰寫了一個解決方法。希望能幫助到你。
def check_found(val: str=None, substring: str=None):
return not val.find(substring) == -1 # .find returns -1 if not found
for file in f:
print(check_found(file, 'csv_store'))
# result
False
True
True
uj5u.com熱心網友回復:
在 Python 中,bool(-1)計算結果為True. 該str.find方法的檔案說如果找不到字串,則回傳-1
因此,無論您是否找到您正在尋找的針頭,您的狀況將始終評估為True。
您可以考慮測驗結果的積極性,或使用index在失敗時引發例外的類似方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488447.html
