如何根据项目的出现情况对Python列表进行切片?

2024-04-25 06:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如果给出以下列表lst

import random as rnd, operator as op, itertools as it
from functools import partial

lst = [x for x in it.islice(it.cycle(range(1,10)), 50)]
idx = set(rnd.sample(range(len(lst)), 10))
for i in idx:
    lst.insert(i, 0)

如何按0的出现次数进行切片?你知道吗

我目前的策略是:

new_lst = [list(g) for k,g in it.groupby(lst, partial(op.eq, 0))]
new_lst
[[1, 2, 3, 4],
 [0],
 [5, 6, 7, 8, 9],
 [0],
 [1, 2],
 [0],
 [3, 4],
 [0],
 [5],
 [0],
 [6, 7, 8],
 [0],
 [9, 1, 2, 3, 4, 5, 6, 7],
 [0],
 [8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0],
 [1, 2, 3, 4, 5, 6],
 [0],
 [7],
 [0],
 [8, 9, 1, 2, 3, 4, 5]]

注意,在结果new_lst中,我仍然有分隔符,因此要获得所需的结果,我必须再次迭代:

new_lst = [i for i in new_lst if 0 not in i]
new_lst
[[1, 2, 3, 4],
 [5, 6, 7, 8, 9],
 [1, 2],
 [3, 4],
 [5],
 [6, 7, 8],
 [9, 1, 2, 3, 4, 5, 6, 7],
 [8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6],
 [7],
 [8, 9, 1, 2, 3, 4, 5]]

有没有更有效的方法?你知道吗


Tags: inimport列表newforasrangeit
2条回答

您也可以尝试此方法,它不使用库:

lst = [0, 1, 2, 3, 4, 0, 0, 5, 6, 0, 7, 8, 9, 10, 0, 0]

# indices of all zeroes
indexes = [-1] + [i for i, e in enumerate(lst) if e == 0]

# get all the sublists
result = []
for start, end in zip(indexes, indexes[1:]):
    result.append(lst[start+1:end])

# add last if any
result.append(lst[end+1:])

# filter out empty lists
print([x for x in result if x])

输出:

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

只需在键上使用一个条件k

new_lst = [list(g) for k,g in it.groupby(lst, partial(op.eq, 0)) if not k]

或者更直接地使用op.ne

new_lst = [list(g) for k,g in it.groupby(lst, partial(op.ne, 0)) if k]

或不带partial(注意0 .__ne__中的空格,或使用(0).__ne__):

new_lst = [list(g) for k,g in it.groupby(lst, 0 .__ne__) if k]

相关问题 更多 >