怎么计算数组中同样元素的个数

qq403720014 2012-05-01 11:06:23
怎么计算数组中同样元素的个数
用count可以实现吗


例如@a=(a,a,b,c,c,c,d)
怎么实现输出a 2
b 1
c 3
d 1


要求不仅仅是计算,还要输出唯一的元素和次数,麻烦大家了。
...全文
731 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zmnc001 2012-05-10
  • 打赏
  • 举报
回复
看了一下帮助“Build an unordered collection of unique elements.”还真是无序的。
多谢!
panghuhu250 2012-05-09
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 的回复:]

请教3楼,为何print出来的序列是a c b d的顺序,而不是a b c d的顺序呢?多谢!……
[/Quote]

python的set是无序的.
zmnc001 2012-05-09
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]
直接统计

Python code

>>> s = ['a','a','b','c','c','c','d']
>>> for x in set(s):
print x, s.count(x)


a 2
c 3
b 1
d 1
>>>
[/Quote]

请教3楼,为何print出来的序列是a c b d的顺序,而不是a b c d的顺序呢?多谢!
angel_su 2012-05-07
  • 打赏
  • 举报
回复
@a=貌似perl来的,我没学不会...
fibbery 2012-05-07
  • 打赏
  • 举报
回复
use strict;
use warnings;

my %statistcs;
my @a=('a','a','b','c','c','c','d');
foreach my $item (@a)
{
$statistcs{$item}++;
}

foreach my $item (keys(%statistcs))
{
print("The number of item $item is $statistcs{$item}\n");
}



D:\Debug>perl test.pl
The number of item c is 3
The number of item a is 2
The number of item b is 1
The number of item d is 1
libralibra 2012-05-06
  • 打赏
  • 举报
回复
直接统计
>>> s = ['a','a','b','c','c','c','d']
>>> for x in set(s):
print x, s.count(x)


a 2
c 3
b 1
d 1
>>>
tim_spac_126 2012-05-02
  • 打赏
  • 举报
回复
counter = {}
for ch in array:
counter.setdefault(ch,[]).append(1)
for ch, lst in counter.items():
print ch, sum(lst)
农村的我 2012-05-02
  • 打赏
  • 举报
回复
ta=('a','a','b','c','c','c','d')
la=[]
lth=len(ta)

for i in range(lth):
la.append(ta[i])#转化为列表

la.sort()#使相同元素相邻
da={}#字典储存结果
i=0
while i<lth:
da[la[i]]=la.count(la[i])
i=i+da[la[i]]

print da







37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧