大家好,我正在從事一個學校專案,我們正在撰寫代碼以在 python 中實作我們自己構建的 unix shell。我被 ls -a 命令困在這個小部分上,我想忽略 .(dot) 檔案。這是我的代碼,我不知道如何完成它。
if 'a' not in flags:
for files in file_list:
if files.startswith('.'):
#ignore . files
uj5u.com熱心網友回復:
有幾個選項可用:
- 反轉條件:
if 'a' not in flags: for files in file_list: if not files.startswith('.'): print(files) - 如果檔案匹配,則繼續回圈而不列印:
if 'a' not in flags: for files in file_list: if files.startswith('.'): continue print(files) - 將這兩個條件組合在一起,使代碼嵌套更少
for files in file_list: if 'a' in flags or (not files.startswith('.')): print(files) - 從迭代中分離過濾:
if 'a' not in flags: file_list = [files for files in file_list if not files.startswith('.') # more if-statements to process other flags of interest, # e.g. if a flag for sorting is specified, sort the files for files in file_list: print(files)
在最簡單的情況下,我會傾向于第一個選項,或者如果您需要可擴展到更多標志的可擴展邏輯,我會傾向于最后一個選項。我使用了速記的串列推導,但您也可以呼叫處理串列的函式,撰寫更新檔案串列的手寫回圈,或其他方式。
我還要補充一點,你呼叫的變數一次files參考一個檔案,所以它應該被命名file(或者如果檔案名和檔案物件之間存在歧義,也許file_name)。為了與您現有的代碼保持一致,我將其保留在答案中。
uj5u.com熱心網友回復:
for files in file_list:
if files.startswith('.dot'):
continue
for files in file_list:
if not files.startswith('.dot'):
do_something()
for files in file_list:
if files.startswith('.dot'):
pass
uj5u.com熱心網友回復:
#Creates empty list
files_no_period = [
]
if 'a' not in flags:
for file in file_list:
if not files.startswith('.'):
files_no_period.append(file)
#Prints files in list
print ("\n".join(files_no_period))
"""
- Changed 'for files' to 'for file', just because you are going through each file on at a time.
- Changed if statement to if not, meaning if file isn't starting with a '.'.
- Add each file that doesn't start with '.' to a list.
- List all files from the list of files that don't start with a '.'.
"""
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429198.html
標籤:Python python-3.x
下一篇:元素陣列緩沖區不影響結果影像
