作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个包含如下文件名的数组:
['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png', '003_1.png', '003_2.png', '003_3.png', '003_4.png', ....]
我想像这样快速将这些文件分组到多个数组中:
[['001_1.png', '001_2.png', '001_3.png'], ['002_1.png', '002_2.png'], ['003_1.png', '003_2.png', '003_3.png', '003_4.png'], ...]
谁能告诉我如何在 python 中用几行代码完成它?
最佳答案
如果您的数据已经按文件名排序,您可以使用 itertools.groupby
:
files = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png',
'003_1.png', '003_2.png', '003_3.png']
import itertools
keyfunc = lambda filename: filename[:3]
# this creates an iterator that yields `(group, filenames)` tuples,
# but `filenames` is another iterator
grouper = itertools.groupby(files, keyfunc)
# to get the result as a nested list, we iterate over the grouper to
# discard the groups and turn the `filenames` iterators into lists
result = [list(files) for _, files in grouper]
print(list(result))
# [['001_1.png', '001_2.png', '001_3.png'],
# ['002_1.png', '002_2.png'],
# ['003_1.png', '003_2.png', '003_3.png']]
否则,您可以将代码基于 this recipe ,这比排序列表然后使用 groupby
更有效。
输入:您的输入是一个平面列表,因此请使用常规 ol' 循环对其进行迭代:
for filename in files:
组标识符:文件按前 3 个字母分组:
group = filename[:3]
输出:输出应该是嵌套列表而不是字典,这可以用
result = list(groupdict.values())
综合:
files = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png',
'003_1.png', '003_2.png', '003_3.png']
import collections
groupdict = collections.defaultdict(list)
for filename in files:
group = filename[:3]
groupdict[group].append(filename)
result = list(groupdict.values())
print(result)
# [['001_1.png', '001_2.png', '001_3.png'],
# ['002_1.png', '002_2.png'],
# ['003_1.png', '003_2.png', '003_3.png']]
阅读the recipe answer了解更多详情。
关于Python - 将数组拆分为多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50169588/
我是一名优秀的程序员,十分优秀!