1

I have the following list:

x=["A", "B", "B", "C", "B", "A", "D", "D", "A", "B", "A", "D"]

I wonder how does one partition into sublists of length 2 with offset 1 such that one gets:

#[["A", "B"], ["B", "B"], ["B", "C"], ["C", "B"], ["B", "A"], ["A", 
# "D"], ["D", "D"], ["D", "A"], ["A", "B"], ["B", "A"], ["A", "D"]]

Also is there a generalised method for this? For example for different size of partition and different offsets? Suppose I want to partition into sublists of 3 with offset 2: for which I'd get

#[["A", "B", "B"], ["B", "C", "B"], ["B", "A", "D"], ["D", "D", 
# "A"], ["A", "B", "A"]]

Is it possible to write this as a function, so for a given list, with given partition size and given number of offset it finds the sublists?

Wiliam
  • 1,078
  • 10
  • 21

2 Answers2

4

You can use a slice of the list after the first element and do this with zip

    >>> x=["A", "B", "B", "C", "B", "A", "D", "D", "A", "B", "A", "D"]
    >>> [list(a) for a in zip(x,x[1:])]
    [['A', 'B'], ['B', 'B'], ['B', 'C'], ['C', 'B'], ['B', 'A'], ['A', 'D'], ['D',
    'D'], ['D', 'A'], ['A', 'B'], ['B', 'A'], ['A', 'D']]
Easton Bornemeier
  • 1,918
  • 8
  • 22
0

Given a list x with n items, you need to create a new list with n-1 items, each item is a pair of items that follow each other. It's easy to do with running over the items of the list from the first item until the second to last, and create a list for every one of those items with that item (x[i]) and the one that comes after him (x[i+1])

result = [[x[i], x[i+1]] for i in range(len(x)-1)]

And for the more generic case:

offset = 2
sublist_size = 3
result = [[x[i + n] for n in range(sublist_size)] for i in range(0, len(x) - sublist_size, offset)]
galfisher
  • 1,122
  • 1
  • 13
  • 24
  • Thanks for this is there a generalised method for this? For example for different size of partition and different offsets? Suppose I want to partition into sublists of 3 with offset 2: for which I'd get [["A", "B", "B"], ["B", "C", "B"], ["B", "A", "D"], ["D", "D", "A"], ["A", "B", "A"]] – Wiliam Aug 07 '18 at 14:35
  • I have edited the question, if you add this to the answer I will accept it. Thank you. – Wiliam Aug 07 '18 at 14:45
  • 1
    although that works, I think you're getting some downvotes because `range(len(x)-1)` is horribly unpythonic compared to `zip` – Jean-François Fabre Aug 07 '18 at 15:33