<p>可以使用<a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">^{<cd1>}</a>和<a href="https://docs.python.org/3/library/os.path.html#os.path.split" rel="nofollow noreferrer">^{<cd2>}</a>作为:</p>
<pre><code>from collections import defaultdict
import os
my_list = ['/User/someuser/file.py', '/tmp/download/file.zip', '/tmp/download/file2.zip', '/', '/usr/local/bin', '/tmp/file.txt']
my_dict = defaultdict(list)
for item in my_list:
if os.path.isdir(item): # To check path is a directory
_ = my_dict[item] # will set default value as empty list
else:
path, file = os.path.split(item)
my_dict[path].append(file)
# where `my_dict` is `dict` object holding value:
# {'/tmp/download': ['file.zip', 'file2.zip'], '/tmp': ['file.txt'], '/usr/local/bin': [], '/': [], '/User/someuser': ['file.py']}
</code></pre>
<p>要将<code>my_dict</code>转换为所需格式的列表,请执行以下操作:</p>
<pre><code>>>> my_dict.items()
[ # Formatted in order to make more readable
('/tmp/download', ['file.zip', 'file2.zip']),
('/tmp', ['file.txt']),
('/usr/local/bin', []),
('/', []),
('/User/someuser', ['file.py'])
]
</code></pre>