简体   繁体   中英

Generate a subset of list in a cyclical manner

x = [1,2,3,4,5,6,7] . y = 3 . Assume y<=len(x)

How do I generate subsets from x of length y such as

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

Assuming that the first subset is x[:3] , how do I keep generating the rest of the subsets?

EDIT 1: My solution based on @Jordan's answer

xs = [1,2,3,4,5,6,7]
y = 3

sublist = None

def cycles(xs, y, prev):
    start = 0 if prev[-1]==xs[-1] else (xs.index(prev[-1])+1)
    sublist = [xs[i % len(xs)] for i in range(start, start + y)]
    start = (start + y) % len(xs)
    return sublist

for _ in range(10):

    if sublist == None:
        prev = xs[0:y]
        prev = cycles(xs, y, prev)
        print("first")
        sublist = prev
    else:
        prev = cycles(xs, y, prev)


    print(prev)

You can keep generating them using a generator. One possible solution (which also works for y > len(x) ):

def cycles(xs, y):
    start = 0
    while True:
        sublist = [xs[i % len(xs)] for i in range(start, start + y)]
        start = (start + y) % len(xs)
        yield sublist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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