简体   繁体   中英

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

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

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.

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