以下是一个示例代码,可将一个行数较多的二维列表按列分割成多个列表。
def split_rows_by_columns(data, num_columns):
num_rows = len(data)
num_rows_per_column = num_rows // num_columns
remainder = num_rows % num_columns
split_data = []
start_index = 0
for i in range(num_columns):
end_index = start_index + num_rows_per_column
if i < remainder:
end_index += 1
split_data.append(data[start_index:end_index])
start_index = end_index
return split_data
# 示例数据
data = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30]]
num_columns = 3
# 按列分割行数
split_data = split_rows_by_columns(data, num_columns)
print(split_data)
输出结果为:
[[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]],
[[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]],
[[21, 22, 23, 24, 25], [26, 27, 28, 29, 30]]]
上述代码中的 split_rows_by_columns
函数接受两个参数:data
表示要分割的二维列表,num_columns
表示要分割成的列数。首先计算每列应有的行数 num_rows_per_column
,然后计算剩余的行数 remainder
。接下来使用一个循环来依次截取每列的行数,并将截取的部分添加到 split_data
列表中。最后返回分割后的结果。
上一篇:按列分隔文本文件的行
下一篇:按列分区:数据被截断到另一个分区