简体   繁体   English

从列表中创建唯一项目的子列表

[英]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".是否可以从“mylist”创建“myresultlist”。

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...一个带有第三个参数和zip()的小range()可以让你到达那里,我想......

# 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.基本上使用 set 进行重复数据删除,然后转换回列表。 Repeat n number of times, where n = list length / set length重复 n 次,其中 n = 列表长度 / 设置长度

[Edit] Saw the example in new edit of question. [编辑] 在问题的新编辑中看到了这个例子。 Above solution will not work for that scenario.上述解决方案不适用于该场景。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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