如何在列表中生成10个连续数字的组?

时间:2014-10-14 21:37:59

标签: python list

我正在尝试以十个为一组生成一个连续数字列表。例如,让我们从109个数字列表开始:

mylist = range(1,110,1)

我知道我可以使用range(1,110,10)生成一个10的间隔列表,这会产生:

[1, 11, 21, 31, 41, 51, 61, 71, 81, 91, 101]

如何生成十个一组的连续数字列表,如下所示?

[[1,2,3,4,5,6,7,8,9,10],[11,12,13,14,15,16,17,18,19,20], ...]

3 个答案:

答案 0 :(得分:9)

您可以使用列表理解:

[range(i, i + 10) for i in range(1, 102, 10)]

演示:

>>> from pprint import pprint
>>> [range(i, i + 10) for i in range(1, 102, 10)]
[[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], [31, 32, 33, 34, 35, 36, 37, 38, 39, 40], [41, 42, 43, 44, 45, 46, 47, 48, 49, 50], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60], [61, 62, 63, 64, 65, 66, 67, 68, 69, 70], [71, 72, 73, 74, 75, 76, 77, 78, 79, 80], [81, 82, 83, 84, 85, 86, 87, 88, 89, 90], [91, 92, 93, 94, 95, 96, 97, 98, 99, 100], [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]]
>>> pprint(_)
[[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],
 [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
 [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
 [51, 52, 53, 54, 55, 56, 57, 58, 59, 60],
 [61, 62, 63, 64, 65, 66, 67, 68, 69, 70],
 [71, 72, 73, 74, 75, 76, 77, 78, 79, 80],
 [81, 82, 83, 84, 85, 86, 87, 88, 89, 90],
 [91, 92, 93, 94, 95, 96, 97, 98, 99, 100],
 [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]]

答案 1 :(得分:2)

您可以使用嵌套列表推导来生成这样的列表。

[[10*i + j for j in range(1,11)] for i in range(10)]

输出

[[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],
 [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
 [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
 [51, 52, 53, 54, 55, 56, 57, 58, 59, 60],
 [61, 62, 63, 64, 65, 66, 67, 68, 69, 70],
 [71, 72, 73, 74, 75, 76, 77, 78, 79, 80],
 [81, 82, 83, 84, 85, 86, 87, 88, 89, 90],
 [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]

答案 2 :(得分:1)

或者,您可以将它们组合在一起。

def grouper(iterable, n):
    # from itertools recipes
    return zip(*[iter(iterable)] * n)

full_range = range(1, 101)

grouped_list = list(grouper(full_range,10))

结果是:

[(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),
 (31, 32, 33, 34, 35, 36, 37, 38, 39, 40),
 (41, 42, 43, 44, 45, 46, 47, 48, 49, 50),
 (51, 52, 53, 54, 55, 56, 57, 58, 59, 60),
 (61, 62, 63, 64, 65, 66, 67, 68, 69, 70),
 (71, 72, 73, 74, 75, 76, 77, 78, 79, 80),
 (81, 82, 83, 84, 85, 86, 87, 88, 89, 90),
 (91, 92, 93, 94, 95, 96, 97, 98, 99, 100)]
# a list of tuples, if you need it to be a list of lists:
# [list(group) for group in grouper(full_range, 10)]