gpt4 book ai didi

Python - 将数组拆分为多个数组

转载 作者:行者123 更新时间:2023-11-28 20:33:39 27 4
gpt4 key购买 nike

我有一个包含如下文件名的数组:

['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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com