简体   繁体   English

获取列表的每个片段

[英]Getting every slice of a list

I've been through itertools inside and out and I cannot figure out how to do the following. 我从里到外都经历过itertools,我无法弄清楚如何做到以下几点。 I want to take a list. 我想列一个清单。

x = [1,2,3,4,5,6,7,8] and I want to get a new list: x = [1,2,3,4,5,6,7,8]我希望得到一个新列表:

y = [[1],[1,2],[1,2,3],.......[2],[2,3],[2,3,4].....[8]]

I need a list of all slices, but not combinations or permutations. 我需要所有切片的列表,但不需要组合或排列。

x = list(zip(x[::2], x[1::2])) is close, but doesn't do exactly what I'm hoping x = list(zip(x[::2], x[1::2]))很接近,但并不完全正是我所希望的

Use combinations not of x , but of the range of possible slice indices (including one past the end, thus len(x)+1 , since slices are exclusive on the end) to make the slice end points, then use them to slice x : 使用不是x combinations ,但是可能的切片索引的range (包括一个超过结束,因此len(x)+1 ,因为切片在末尾是独占的)来制作切片端点,然后使用它们来切片x

from itertools import combinations

y = [x[s:e] for s, e in combinations(range(len(x)+1), 2)]

That gets exactly what you're going for as straightforwardly as possible. 这正是你想要的尽可能直截了当的。 If you want (possibly) faster map based code, you can rephrase it as ( list wrapper unnecessary on Python 2): 如果你想(可能)更快的基于map的代码,你可以将其改写为(在Python 2上不需要list包装器):

from itertools import combinations, starmap

y = list(map(x.__getitem__, starmap(slice, combinations(range(len(x)+1), 2))))

which gets the same result, but without any Python bytecode execution per-item, which might run faster (implementation dependent). 获得相同的结果,但没有任何Python字节码执行每个项目, 可能运行得更快(依赖于实现)。

You can utilize list comprehension if you insist on a one-liner: 如果你坚持单行,你可以利用列表理解:

> x=[1,2,3,4]
> [x[a:b+1] for a in range(len(x)) for b in range(len(x)) if a<=b]

[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]] [[1],[1,2],[1,2,3],[1,2,3,4],[2],[2,3],[2,3,4],[3] ,[3,4],[4]]

Or you can even get rid of that if : 或者,你甚至可以摆脱的if

> [x[a:b+1] for a in range(len(x)) for b in range(a, len(x))]

You can try this: 你可以试试这个:

x = [1,2,3,4,5,6,7,8]
y = [x[b:i+1] for b in range(len(x)) for i in range(len(x))]
final_list = list(filter(lambda x:x, y))

Output: 输出:

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

I think this is a good aproach, an iterative way, I could understand it well: 我认为这是一个很好的方法,一种迭代的方式,我能理解它:

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

res = []
ln= len(lst)


for n in range(ln):
  for ind in range(n+1, ln+1):
    res.append(lst[n:ind])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM