假设我有一个文件列表
files = ['s1.txt', 'ai1.txt', 's2.txt', 'ai3.txt']
Run Code Online (Sandbox Code Playgroud)
我需要根据它们的数量将它们分类到子列表中
files = [['s1.txt', 'ai1.txt'], ['s2.txt'], ['ai3.txt']]
Run Code Online (Sandbox Code Playgroud)
我可以写一堆循环,但我想知道是否有更好的方法来做到这一点?
这是一个完整的工作示例,基于defaultdict:
import re
from collections import defaultdict
files = ['s1.txt', 'ai1.txt', 's2.txt', 'ai3.txt']
def get_key(fname):
return int(re.findall(r'\d+', fname)[0])
d = defaultdict(list)
for f in files:
d[get_key(f)].append(f)
out = [d[k] for k in sorted(d.keys())]
print(out)
Run Code Online (Sandbox Code Playgroud)
这会产生:
[['s1.txt', 'ai1.txt'], ['s2.txt'], ['ai3.txt']]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
310 次 |
| 最近记录: |