Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按正确顺序列出计数_Python_List_Count_Compression - Fatal编程技术网

Python 按正确顺序列出计数

Python 按正确顺序列出计数,python,list,count,compression,Python,List,Count,Compression,名单如下: names=['fred', 'fred', 'fred', 'bill', 'bill', 'ted', 'ted', 'ted', 'ted'] 我想返回每个姓名的计数列表: desired_list=[3,2,4] 注意:每个名称的计数顺序与“名称”列表中的顺序相同 我尝试过的代码: 输入: 输出: [4, 3, 2] ……但顺序不对。它应该是[3,2,4]…与名称列表中的名称顺序相同。使用 使用 使用itertools中的groupby和列表理解的另一个选项是: f

名单如下:

names=['fred', 'fred', 'fred', 'bill', 'bill', 'ted', 'ted', 'ted', 'ted']
我想返回每个姓名的计数列表:

desired_list=[3,2,4]
注意:每个名称的计数顺序与“名称”列表中的顺序相同

我尝试过的代码: 输入:

输出:

[4, 3, 2]
……但顺序不对。它应该是[3,2,4]…与名称列表中的名称顺序相同。

使用


使用



使用
itertools
中的
groupby
和列表理解的另一个选项是:

from itertools import groupby
names=['fred', 'fred', 'fred', 'bill', 'bill', 'ted', 'ted', 'ted', 'ted']

res = [len(list(g[1])) for g in groupby(names)]
print(res)
返回:

[3, 2, 4]

使用
itertools
中的
groupby
和列表理解的另一个选项是:

from itertools import groupby
names=['fred', 'fred', 'fred', 'bill', 'bill', 'ted', 'ted', 'ted', 'ted']

res = [len(list(g[1])) for g in groupby(names)]
print(res)
返回:

[3, 2, 4]

太好了,谢谢你……那么你怎么去掉“dict_值”……那么它就这么写了:[3,2,4]太好了,谢谢你……那么你怎么去掉“dict_值”……那么它就这么写:[3,2,4]
[3, 2, 4]