计算列表中每个项目的编号。 [英] Counting number of each item in a list.
问题描述
我有一个类似这样的列表:
StringA
StringC
StringB
StringA
StringC
StringD
StringA
....
基本上我想知道是否有一种简单的方法可以返回列表中每个字符串中有多少
,如下所示:
StringA - 3
StringB - 1
StringC - 2
StringD - 1
我想最简单的方法是将它转换为2 $
维数组?有没有简单的方法?
谢谢。
I have a list a little something like this:
StringA
StringC
StringB
StringA
StringC
StringD
StringA
....
etc.
Basically I was wondering if there was an easy way to return how many
of each string are in the list, something like this:
StringA - 3
StringB - 1
StringC - 2
StringD - 1
I suppose that the easiest way to do that is to convert it to a 2
dimensional array? Is there any easy way?
Thanks.
推荐答案
" sophie_newbie" < PA ********** @ gmail.com>写道:
"sophie_newbie" <pa**********@gmail.com> writes:
我想最简单的方法是将它转换成2维数组吗?有没有简单的方法?
I suppose that the easiest way to do that is to convert it to a 2
dimensional array? Is there any easy way?
使用哈希表。未经测试:
h = 0
你的__ $中的
:
h [x] = h.get(x,0)+ 1
然后你可以使用像排序(h.items())这样的东西来获得一个排序列表
这些计数。
Use a hash table. Untested:
h = 0
for x in your_list:
h[x] = h.get(x, 0) + 1
You can then use something like sorted(h.items()) to get a sorted list
of those counts.
sophie_newbieaécrit:
sophie_newbie a écrit :
我有一个类似这样的列表:
StringA
StringC
StringB
StringA
StringC
StringD
StringA
...
基本上我想知道是否有一个简单的返回列表中每个字符串的数量的方式,如下所示:
StringA - 3
StringB - 1
StringC - 2
StringD - 1
I have a list a little something like this:
StringA
StringC
StringB
StringA
StringC
StringD
StringA
...
etc.
Basically I was wondering if there was an easy way to return how many
of each string are in the list, something like this:
StringA - 3
StringB - 1
StringC - 2
StringD - 1
有。
str_list = [''StringA'',''StringC'',' 'StringB'',
''StringA'',''StringC'',''StringD'',
''StringA'']
str_counts = dict((s,str_list.count(s)for s in set(str_list))
There is.
str_list = [''StringA'', ''StringC'', ''StringB'',
''StringA'', ''StringC'', ''StringD'',
''StringA'' ]
str_counts = dict((s, str_list.count(s) for s in set(str_list))
Hey Bruno,
我尝试使用时语法错误无效你的str_counts =
dict((s,str_list.count(s)for s in set(str_list))"一点代码?也许
有一个丢失的括号或逗号?或许我需要导入
的东西。
非常感谢你的帮助。
Hey Bruno,
I got an invalid syntax error when i tried using your "str_counts =
dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe
there is a missing bracket or comma? Or maybe I need to import
something.
Thanks so much for your help.
>
这篇关于计算列表中每个项目的编号。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!