JimmyOppa
JimmyOppa

Reputation: 67

Create sub-lists of the unique items from a list

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']

Upvotes: 3

Views: 63

Answers (2)

JonSG
JonSG

Reputation: 13067

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']
]

Upvotes: 2

Ashutosh
Ashutosh

Reputation: 159

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.

Upvotes: 1

Related Questions