在python中,我想获取一个列表并将其分成列表列表。 如果我有一个列表,该列表长20个数字,那么我想将其变成两个列表的列表,每个列表长5个数字。
输入
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
输出
new_nums = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]
答案 0 :(得分:0)
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
result = [nums[x:x+5] for x in range(0, len(nums), 5)]
print(result)
#Output:
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]