python-3.x - 将列表分成块的更快方法
问题描述
我有一个dict
需要分成块的 s 列表:
input_size = len(input_rows) # num of dicts
slice_size = int(input_size / 4) # size of each chunk
remain = input_size % 4 # num of remaining dicts which cannot be divided into chunks
result = [] # initializes the list for containing lists of dicts
iterator = iter(input_rows) # gets a iterator on input
for i in range(4):
result.append([]) # creates an empty list as an element/block in result for containing rows for each core
for j in range(slice_size):
result[i].append(iterator.__next__()) # push in rows into the current list
if remain:
result[i].append(iterator.__next__()) # push in one remainder row into the current list
remain -= 1
input_rows
包含dict
s 的列表,将其分成 4 个块/片;如果有剩余dict
的s不能被平均分成4个chunk,这些剩余dict
的s会被放入其中的一些chunk中。一个列表 ( result
) 用于包含每个块,而该块又包含一个dict
s 列表。
我想知道如何以更有效的方式做到这一点。
解决方案
使用标准库
R = list()
L = list(range(10))
remainder = int(len(L) % 4)
chunk_size = int(len(L) / 4)
position = 0
while position < len(L):
this_chunk = chunk_size
if remainder:
this_chunk += 1
remainder -= 1
R.append(L[position:this_chunk + position])
position += this_chunk
print(R)
[[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]]
这应该会更快,因为您迭代和插入的次数要少得多。在这种情况下,您实际上只是根据列表元数据的计算抓取 4 个切片并插入 4 次...
此外,这特别是numpy.array_split *的原因:这应该更快......
>>> print(*np.array_split(range(10), 4))
[0 1 2] [3 4 5] [6 7] [8 9]
编辑:由于评论部分的反馈和上述答案中的潜在错误(在输入列表大小小于潜在块数的情况下)这里是一个替代函数,它做同样的事情,但总是会产生请求的块数
def array_split(input_list, chunks):
chunk_size = int(len(input_list) / chunks)
remainder = len(input_list) % chunks
new_list = list()
position = 0
while position < len(input_list):
this_chunk = chunk_size
if remainder:
this_chunk, remainder = this_chunk + 1, remainder - 1
new_list.append(input_list[position:this_chunk + position])
position += this_chunk
new_list.extend([[] for _ in range(chunks - len(new_list))])
return new_list
def unit_test():
L = [1, 2]
print(array_split(L, 4))
L = list(range(13))
print(array_split(L, 3))
L = list(range(22))
print(array_split(L, 5))
>>> unit_test()
[[1], [2], [], []]
[[0, 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]]
推荐阅读
- angular - Dotnet Core、Angular 5 SPA 和 Microsoft Graph API
- python - Python Shapely - 查找两个多多边形的部分是否重叠
- android-studio - 如何在 Android Studio 中的 buttonView 前面获取 imageButton?
- java - 创建一种决定单词元音和声的方法
- xslt - 你可以在 Dita-ot 插件中从 XSL 访问 dita map keydef 变量吗
- vbscript - 使用 VBScript 过滤 Word 文档
- c# - 如何在 MVVM 架构中将动画视图播放与 LottieForms 绑定?
- c# - Visual Studio 2017 Collapsing 也删除了未使用的使用
- javascript - 将 html 锚点更改为 markdown
- android - 不同设备上的 Android 语音识别器