如何通过连续前缀将文件名分组到列表中?
我有多个具有相同后缀的文件(_01_020301.txt
)和不同的数字前缀。目标是通过连续前缀将它们分组为列表。
这是一个示例:
09456_01_020301.txt
09457_01_020301.txt
09458_01_020301.txt
09459_01_020301.txt
09460_01_020301.txt
09465_01_020301.txt
09466_01_020301.txt
09467_01_020301.txt
09468_01_020301.txt
因为09456〜09460和09465〜09468是两个连续的组,因此结果应为:
[['09456_01_020301.txt',
'09457_01_020301.txt',
'09458_01_020301.txt',
'09459_01_020301.txt',
'09460_01_020301.txt'],
['09465_01_020301.txt',
'09466_01_020301.txt',
'09467_01_020301.txt',
'09468_01_020301.txt']]
I have multiple files which have the same suffix (_01_020301.txt
) and different number prefixes. The goal is to group them into lists by the consecutive prefix.
Here's an example:
09456_01_020301.txt
09457_01_020301.txt
09458_01_020301.txt
09459_01_020301.txt
09460_01_020301.txt
09465_01_020301.txt
09466_01_020301.txt
09467_01_020301.txt
09468_01_020301.txt
Because 09456~09460 and 09465~09468 are two consecutive groups, the result should be:
[['09456_01_020301.txt',
'09457_01_020301.txt',
'09458_01_020301.txt',
'09459_01_020301.txt',
'09460_01_020301.txt'],
['09465_01_020301.txt',
'09466_01_020301.txt',
'09467_01_020301.txt',
'09468_01_020301.txt']]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一个解决方案是,使用
itertools.groupbys.groupbys.groupbys.groupby
:打印:
Another solution, using
itertools.groupby
:Prints:
这是使用简单循环的一种方法:
输出:
Here is one way using a simple loop:
output:
对于输入的假设为str(例如,
.csv
文件),我通过比较以前的后缀和当前后缀来创建以下代码。With assumtion of the input is a str (for example,
.csv
file), I created following code by comparing previous suffix and current suffix.