如何使用python在其他元素之间切片元素

时间:2019-03-05 22:49:01

标签: python-3.x

我有一个带数字的列表,我想对列表上存在的数字192之间的所有元素进行切片并将它们传递给列表

我的列表

[192,0,1,0,1,192,12,0,5,0,1,0,1,66,218,0,10,5,115,116,97,116,115, 1,108,192,20,192,53,0,1,0,1,0,0,0,162,0,4,74,125,133,155,192,53,0,1,0, 1,0,0,0,162,0,4,74,125,133,156,192,53,0,1,0,1,0,0,0,162,0,4,4,74,125, 133,154,192,53,0,1,0,1,0,0,0,162,0,4,74,125,133,157]

我想要这样的东西

[192,0,1,0,1]

[192,12,0,5,0,1,0,1,66,218,0,10,5,115,116,97,116,115,1,108]

[192,20,192,53,0,1,0,1,0,0,0,162,0,4,74,125,133,155]

直到列表末尾。

2 个答案:

答案 0 :(得分:1)

这是一种可行的方法:

# input list
lst = [192, 0, 1, 0, 1, 192, 12, 0, 5, 0, 1, 0, 1, 66, 218, 0, 10, 5, 115, 116, 97, 116, 115, 1, 108, 192, 20, 192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 155, 192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 156, 192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 154, 192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 157]
# list of indexes where 192 is found,
# plus one extra index for the final slice
indexes = [i for i, n in enumerate(lst) if n == 192] + [len(lst)]
# create the slices between consecutive indexes
[lst[indexes[i]:indexes[i+1]] for i in range(len(indexes) - 1)]

结果将是:

[[192, 0, 1, 0, 1],
 [192, 12, 0, 5, 0, 1, 0, 1, 66, 218, 0, 10, 5, 115, 116, 97, 116, 115, 1, 108],
 [192, 20],
 [192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 155],
 [192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 156],
 [192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 154],
 [192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 157]]

答案 1 :(得分:1)

您可以使用itertools.groupby构建一个生成器,该生成器使用192的相等方法作为键函数,将生成器的输出与zip配对,然后使用itertools.chain.from_iterable来加入配对(下面的示例假定您的列表存储在变量l中)

from itertools import groupby, chain
i = (list(g) for _, g in groupby(l, key=(192).__eq__))
[list(chain.from_iterable(p)) for p in zip(i, i)]

这将返回:

[[192, 0, 1, 0, 1],
 [192, 12, 0, 5, 0, 1, 0, 1, 66, 218, 0, 10, 5, 115, 116, 97, 116, 115, 1, 108],
 [192, 20],
 [192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 155],
 [192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 156],
 [192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 154],
 [192, 53, 0, 1, 0, 1, 0, 0, 0, 162, 0, 4, 74, 125, 133, 157]]