我试图想出一个函数,它接受一个输入x并将一个大的列表与元素x * x的数量分成x个较小的列表,每个列表中包含x个元素 例如:
big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
def split_list (x):
big_list = pairs (x)
small_list = [big_list[0:x] for x in range (x)]
我的输出必须是:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
但我没有得到它,你推荐什么?
答案 0 :(得分:7)
你可以试试这个:
big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
def split_list (x):
return [big_list[i:i+x] for i in range(0, len(big_list), x)]
print(split_list(4))
输出:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
答案 1 :(得分:2)
首先,您希望使用平方根来获取大小,因此,对于大小为n
的列表,您将拥有m x m
矩阵m = n ** 0.5
。让我们首先定义您的功能:
def square(array):
n = len(array)
m = int(n ** 0.5)
由于列表大小必须是整数,因此我们必须在结果上调用int
。接下来,我们希望每次从0
开始计数i
至n
m
,从m
开始执行i
元素:
def square(array):
n = len(array)
m = int(n ** 0.5)
result = []
for i in range(0, n, m):
result.append(array[i:i + m])
return result
就是这样。
或者,s=lambda a:(lambda m:[a[i*m:i*m+m]for i in range(m)])(int(len(a)**.5))
答案 2 :(得分:2)
我一直都在使用这段代码。
def chunkify(items, chunk_len):
return [items[i:i+chunk_len] for i in range(0,len(items),chunk_len)]
答案 3 :(得分:2)
这是一个解决方案:
def split_list(big_list, x):
list_size = len(big_list)
splits = int(list_size / x)
return [big_list[k*x:k*x+x] for k in range(splits)]
big_list = [i+1 for i in range(16)]
print(big_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
small_list = split_list(big_list, 4)
print(small_list)
# [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
small_list = split_list(big_list, 2)
print(small_list)
# [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]]
small_list = split_list(big_list, 3)
print(small_list)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
答案 4 :(得分:1)
为什么不使用numpy
:
>>> import numpy as np
>>> big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> a=np.array(big_list)
>>> a
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
>>> n=int(len(big_list)**0.5)
>>> a.reshape(n,n)
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
或只是:
>>> big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> n=int(len(big_list)**0.5)
>>> new_list=[big_list[i:i+n] for i in range(0, len(big_list), n)]
>>> new_list
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]