Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

python - Getting every slice of a list

I've been through itertools inside and out and I cannot figure out how to do the following. I want to take a list.

x = [1,2,3,4,5,6,7,8] and I want to get a new list:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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):

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...