擅长:python、mysql、java
<p>可以使用<a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">groupby</a>和<a href="https://docs.python.org/2/library/os.path.html" rel="nofollow noreferrer">os.path</a></p>
<pre><code>from itertools import groupby
import os
L = ['/User/someuser/file.py', '/tmp/download/file.zip', '/tmp/download/file2.zip', '/', '/usr/local/bin', '/tmp/file.txt']
#if all files have extention, convert '/usr/local/bin' to '/usr/local/bin/'
L_fix = [e if os.path.splitext(e)[1] else os.path.join(e,"") for e in L]
[(k,tuple(map(os.path.basename,v))) for k,v in groupby(L_fix, os.path.dirname)]
</code></pre>
<p>你得到了</p>
<pre><code>[('/User/someuser', ('file.py',)),
('/tmp/download', ('file.zip', 'file2.zip')),
('/', ('',)),
('/usr/local/bin', ('',)),
('/tmp', ('file.txt',))]
</code></pre>