如何将列表划分为较小的不均匀大小的间隔,给出每个间隔的理想初始值和最终值?
我有一个 16383 项的列表。我还有一个单独的值列表,每个间隔应在该值处结束,并且应输入以下值。
我需要使用给定的间隔将每个元素分配给它所属的分区,具体取决于它的值。
我试过阅读东西,但我只遇到了给定原始列表时的情况,人们将它分成大小均匀的分区......
谢谢
布莱斯
If I understand you, you need something like that
>>> a = range(20)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> i = [[1, 5], [5, 8], [8, 20]]
>>> [a[x:y] for x, y in i]
[[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]
or, as Jon Clements suggested in comments:
>>> [a[slice(*s)] for s in i]
[[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]
You can still use slices:
>>> c = [0,3,5,10]
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [l[c[i]:c[i+1]] for i in range(len(c)-1)]
[[0, 1, 2], [3, 4], [5, 6, 7, 8, 9]]
通过列表理解,
>>> a = range(20)
>>> b = [3, 5, 8, 17]
>>> [a[x : y] for x, y in zip([0] + b[:-1], b)]
解释:
[0] + b[:-1]
给
[0, 3, 5, 8]
然后
zip([0] + b[:-1], b)
给出边界
[(0, 3), (3, 5), (5, 8), (8, 17)]
最后遍历列表推导得到
[[0, 1, 2], [3, 4], [5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15, 16]]
还有一种变体:
a = range(20)
b = [3, 5, 8, 17]
map(lambda x, y: a[x : y], [0] + b, b)
给出:
[[0, 1, 2], [3, 4], [5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19]]