创建 n 个列表,每个列表中包含 50 个数字,直到达到 n 个列表。

huangapple go评论60阅读模式
英文:

Create a n number of list to group 50 number in each untill n number reached

问题

我试图创建每50个数字的列表。有人能建议最佳方法吗?

示例:

我有1到112的数字
我想要[[1..50],[51..100],[101..112]]

提前感谢。

英文:

I am trying to create list for each 50 numbers. Could any one suggest best way to do that.

example

I have number from 1 to 112
I want [[1..50],[51..100],[101..112]]

Thanks in advance

答案1

得分: 1

你可以使用一个 while 循环来完成这个任务:

n = 112
i = 1
res = []
while i <= n:
    res.append(list(range(i, min(i+50, n+1)))
    i += 50

res 将会是:

[
  [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, 111, 112]
]

另外,你也可以使用 more_itertools.chunked 来实现相同的效果:

from more_itertools import chunked
n = 112
list(chunked(range(1, n+1), 50))

或者使用列表推导:

n = 112
r = range(1, n+1)
[list(r[i:i+50]) for i in range(0, n, 50)]
英文:

You can do this with a while loop:

n = 112
i = 1
res = []
while i &lt;= n:
    res.append(list(range(i, min(i+50, n+1))))
    i += 50

res will then be:

[
  [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, 111, 112]
]

Edit: alternatively you can use more_itertools.chunked:

from more_itertools import chunked
n = 112
list(chunked(range(1, n+1), 50))

Or a comprehension:

n = 112
r = range(1, n+1)
[list(r[i:i+50]) for i in range(0, n, 50)]

huangapple
  • 本文由 发表于 2023年2月27日 13:24:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定