對一個列表,比如[1,2,2,2,2,3,3,3,4,4,4,4],現在我們需要統計這個列表里的重復項,並且重復了幾次也要統計出來
方法1:
1
2
3
4
|
mylist
=
[
1
,
2
,
2
,
2
,
2
,
3
,
3
,
3
,
4
,
4
,
4
,
4
]
myset
=
set
(mylist)
#myset是另外一個列表,里面的內容是mylist里面的無重復 項
for
item
in
myset:
print
(
"the %d has found %d"
%
(item,mylist.count(item)))
|
方法2:
1
2
3
4
5
6
|
List
=
[
1
,
2
,
2
,
2
,
2
,
3
,
3
,
3
,
4
,
4
,
4
,
4
]
a
=
{}
for
i
in
List
:
if
List
.count(i)>
1
:
a[i]
=
List
.count(i)
print
(a)
|
利用字典的特性來實現。
方法3:
1
2
3
|
>>>
from
collections
import
Counter
>>> Counter([
1
,
2
,
2
,
2
,
2
,
3
,
3
,
3
,
4
,
4
,
4
,
4
])
Counter({
1
:
5
,
2
:
3
,
3
:
2
})
|