Differences between revisions 1 and 2
Revision 1 as of 2008-12-12 01:33:16
Size: 1220
Editor: ZoomQuiet
Comment:
Revision 2 as of 2008-12-12 03:27:40
Size: 1518
Editor: ZoomQuiet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 25: Line 25:
== 方案1 == == 方案1:for ==
Line 48: Line 48:
== 方案2:count() ==
{{{
萧萧 <[email protected]>
reply-to [email protected]
to [email protected]
date Fri, Dec 12, 2008 at 11:18
}}}

{{{
 alist = ['aaa', 'ccc', 'bbb', 'aaa', 'aaa', 'ccc']
 adict = dict([(i, alist.count(i) for i in list(set(alist))])
}}}

TableOfContents

Include(ZPyUGnav)

统计列表重复项

提问

2008/12/11 卢熙 <[email protected]>

  • 要到达以下的效果:

    alist = ['aaa', 'ccc', 'bbb', 'aaa', 'aaa', 'ccc']
    adict = fn(alist)
    print {'aaa': 3, 'bbb': 1, 'ccc': 2}
  • 在实际应用中,len(alist)很有可能超过10万,请问这个fn函数该如何写才能非常高效的完成这个任务?

方案1:for

萧萧 <[email protected]>
reply-to        [email protected]
to      [email protected]
date    Thu, Dec 11, 2008 at 22:51
subject [CPyUG:73576] Re: 如何高效的统计列表里面的重复项

>>> alist = ['aaa', 'ccc', 'bbb', 'aaa', 'aaa', 'ccc']
>>> adict = {}
>>> for i in alist:
...     try:
...             adict[i] += 1
...     except:
...             adict.setdefault(i, 1)
>>> adict

{'aaa': 3, 'bbb': 1, 'ccc': 2} ##endInc

方案2:count()

萧萧 <[email protected]>
reply-to        [email protected]
to      [email protected]
date    Fri, Dec 12, 2008 at 11:18

 alist = ['aaa', 'ccc', 'bbb', 'aaa', 'aaa', 'ccc']
 adict = dict([(i, alist.count(i) for i in list(set(alist))])


反馈

创建 by -- ZoomQuiet [DateTime(2008-12-12T01:33:16Z)]

PageComment2

[:/PageCommentData:PageCommentData]

MiscItems/2008-12-12 (last edited 2009-12-25 07:19:09 by localhost)