Python 中最長公共目錄路徑程式
在本教程中,我們將編寫一個程式,該程式將找到給定路徑列表中的最長公共路徑。讓我們透過一個示例來更清晰地理解問題陳述。
輸入
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django']
/home/tutorialspoint/
我們可以很容易地使用 os 模組解決此問題。 讓我們看看解決此問題的步驟
- 匯入 os 模組。
- 初始化路徑列表以找到最長公共路徑。
- 使用 os.path.commonprefix(paths) 查詢所有路徑的公共字首,並將其儲存在變數中。
- 並使用 os.path.dirname(common_prefix) 從公共字首中提取目錄。
例項
# importing the os module import os # initializing the paths paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorials point/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django'] # finding the common prefix common_prefix = os.path.commonprefix(paths) # extracting the directory from the common prefix longest_common_directory = os.path.dirname(common_prefix) # printing the long common path print(longest_common_directory)
輸出
如果執行以上程式碼,則將獲得以下結果。
home/tutorialspoint
結論
如果您對本教程有任何疑問,請在評論部分中提及。
廣告