3

So I have a list with a pattern. For example. Items of the same kind in order.

mylist = [itemtype1, itemtype1, itemtype1, itemtype2, itemtype2, itemtype2, itemtype3, itemtype3, itemtype3]

myresultlist = [[itemtype1, itemtype2, itemtype3], [itemtype1, itemtype2, itemtype3], [itemtype1, itemtype2, itemtype3]]

Actually, I want to create sub-lists of the unique items.

[itemtype1, itemtype2, itemtype3], [itemtype1, itemtype2, itemtype3], [itemtype1, itemtype2, itemtype3]

Is it possible to create "myresultlist" from "mylist".

Edit: Another example.

mylist = ['jimmy', 'andrew', 'kappy', 'US', 'Spain', 'UK', 'Baseball', 'Football', 'Cricket']

myresultlist = [['jimmy', 'US', 'Baseball'], ['andrew', 'Spain', 'Football'], ['kappy', 'UK', 'Cricket']
JimmyOppa
  • 67
  • 5
  • Does this answer your question? [Splitting a list into N parts of approximately equal length](https://stackoverflow.com/questions/2130016/splitting-a-list-into-n-parts-of-approximately-equal-length) – whackamadoodle3000 Jul 29 '21 at 18:06
  • Are all unique items in list occurring exactly same number of times? i.e. it itemtype1 appears 15 times, will itemtype2 and itemtype3 also appear exactly 15 times in mylist? – Ashutosh Jul 29 '21 at 18:20
  • @Ashutosh Yes! exactly. – JimmyOppa Jul 29 '21 at 18:31
  • @whackamadoodle3000 No, it doesn't answer my question. – JimmyOppa Jul 29 '21 at 18:32
  • @JimmyOppa: With the example in edit, it becomes tricky. Do you always know that there are exactly 3 set of elements, and they are repeated one after other in that order in mylist? – Ashutosh Jul 29 '21 at 18:52
  • @Ashutosh Yes! There will always be 3 set of elements. "mylist" can grow in length but the result will always have sets like ['jimmy', 'US', 'Baseball'] Yes, I know its a very tricky question. I couldn't solve it either, so I thought StackOverflow members might know regarding this. – JimmyOppa Jul 29 '21 at 19:09

2 Answers2

2

A little range() with a 3rd parameter and zip() gets you there I think...

# How many sub-sets to expect
subsets = 3

# your raw data
data = ['jimmy', 'andrew', 'kappy', 'US', 'Spain', 'UK', 'Baseball', 'Football', 'Cricket']

# reshape your raw data into the given number of "subsets"
data_subsets = [
    data[i:i+len(data)//subsets]
    for i in range(0, len(data), subsets)
]

# print your results
print([list(s) for s in zip(*data_subsets)])

This should give you:

[
    ['jimmy', 'US', 'Baseball'],
    ['andrew', 'Spain', 'Football'],
    ['kappy', 'UK', 'Cricket']
]
JonSG
  • 10,542
  • 2
  • 25
  • 36
1

This will work:

mylist = [1, 1, 1, 2, 2, 2, 3, 3, 3]

[list(set(mylist))]*int((len(mylist)/len(set(mylist))))

Output:

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

basically use set to deduplicate and then convert back to list. Repeat n number of times, where n = list length / set length

[Edit] Saw the example in new edit of question. Above solution will not work for that scenario.

Ashutosh
  • 159
  • 6