如果您可以建议我如何按照值的数量编写要拆分列表的脚本,我的意思是:
my_list =[11,11,11,11,12,12,15,15,15,15,15,15,20,20,20] 有11-4,12-2,15-6,20-3项。因此,在exsample范围的下一个列表(0:100)中,我必须对4、2、6、3部分进行拆分,因此我为拆分列表计算了相同的值和函数,但它不适用于list:
div=Counter(my_list).values() ##counts same values in the list
def chunk(it, size):
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())我需要什么:
Out: ([0,1,2,3],[4,5],[6,7,8,9,10,11], etc...] 发布于 2016-09-12 13:55:12
Python 3中的解决方案,如果您只使用counter:
from collections import Counter
my_list =[11,11,11,11,12,12,15,15,15,15,15,15,20,20,20]
count = Counter(my_list)
div= list(count.keys()) # take only keys
div.sort()
l = []
num = 0
for i in div:
t = []
for j in range(count[i]): # loop number of times it occurs in the list
t.append(num)
num+=1
l.append(t)
print(l)输出:
[[0, 1, 2, 3], [4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14]]使用set的交替解决方案
my_list =[11,11,11,11,12,12,15,15,15,15,15,15,20,20,20]
val = set(my_list) # filter only unique elements
ans = []
num = 0
for i in val:
temp = []
for j in range(my_list.count(i)): # loop till number of occurrence of each unique element
temp.append(num)
num+=1
ans.append(temp)
print(ans)编辑:按要求进行更改以获得所需的输出,@Protoss在评论中提到了这一点
my_list =[11,11,11,11,12,12,15,15,15,15,15,15,20,20,20]
val = list(set(my_list)) # filter only unique elements
val.sort() # because set is not sorted by default
ans = []
index = 0
l2 = [54,21,12,45,78,41,235,7,10,4,1,1,897,5,79]
for i in val:
temp = []
for j in range(my_list.count(i)): # loop till number of occurrence of each unique element
temp.append(l2[index])
index+=1
ans.append(temp)
print(ans)输出:
[[54, 21, 12, 45], [78, 41], [235, 7, 10, 4, 1, 1], [897, 5, 79]]在这里,我必须将set转换为list,因为set没有排序,我认为剩余部分是不言自明的。
如果输入不总是排序的话,另一个解决方案(使用OrderedDict):
from collections import OrderedDict
v = OrderedDict({})
my_list=[12,12,11,11,11,11,20,20,20,15,15,15,15,15,15]
l2 = [54,21,12,45,78,41,235,7,10,4,1,1,897,5,79]
for i in my_list: # maintain count in dict
if i in v:
v[i]+=1
else:
v[i]=1
ans =[]
index = 0
for key,values in v.items():
temp = []
for j in range(values):
temp.append(l2[index])
index+=1
ans.append(temp)
print(ans)输出:
[[54, 21], [12, 45, 78, 41], [235, 7, 10], [4, 1, 1, 897, 5, 79]]在这里,我使用OrderedDict来保持输入序列的顺序,在set的情况下,这种顺序是随机的(不可预知的)。
虽然我更喜欢@Ami Tavory的解决方案,这是更多的丙酮。
额外工作:如果有人可以把这个解决方案转换成list comprehension,那就太棒了,因为我试过了,但不能将它转换为list comprehension,如果您成功了,请在评论中发布它,它将帮助我理解。
发布于 2016-09-12 12:49:14
您可以使用enumerate、itertools.groupby和operator.itemgetter
In [45]: import itertools
In [46]: import operator
In [47]: [[e[0] for e in d[1]] for d in itertools.groupby(enumerate(my_list), key=operator.itemgetter(1))]
Out[47]: [[0, 1, 2, 3], [4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14]]这样做的目的如下:
https://stackoverflow.com/questions/39450575
复制相似问题