Python从列表中列出列表

时间:2017-09-05 14:55:45

标签: python list

我的代码现在:random_lst = [1,2,3,4,5,6,7,8,9]

Python在列表中列出列表的实用方法是什么?

我的目标:[[1,2,3],[4,5,6],[7,8,9]]

1 个答案:

答案 0 :(得分:3)

您可以使用:

random_lst = [1,2,3,4,5,6,7,8,9]
new_lst = [random_lst[i:i+3] for i in range(0, len(random_lst), 3)]
print(new_lst) # => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

其他数字:

random_lst = [1,2,3,4,5,6,7,8,9]

def split_n(lst, n):
  return [lst[i:i+n] for i in range(0, len(lst), n)]

print(split_n(random_lst, 1)) # => [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
print(split_n(random_lst, 2)) # => [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
print(split_n(random_lst, 3)) # => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(split_n(random_lst, 4)) # => [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
相关问题