我有两个列表,我想在列表中返回相似值的len()。
A = [1,1,2,2]
B = [3,3,3,3,7,7,7]
在第一个列表中有两次数字1和2,我想在列表中使用len of number值,以查看数字1在第一个列表中重复多少次。在这种情况下,数字2将是2,数字2将是2。
答案 0 :(得分:3)
这是collections.Counter
>>> from collections import Counter
>>> Counter([1,1,2,2])
Counter({1: 2, 2: 2})
>>> Counter([3,3,3,3,7,7,7])
Counter({3: 4, 7: 3})
答案 1 :(得分:2)
一种不使用集合计数器的单行解决方案。
A=[3,4,4,4,3,5,6,8,4,3]
duplicates=dict(set((x,A.count(x)) for x in filter(lambda rec : A.count(rec)>1,A)))
output:
{3: 3, 4: 4}
但是,此解决方案不考虑“拉伸”
答案 2 :(得分:1)
您可以简单地遍历数字并计算相同的数字-或使用itertools.groupby:
def count_em(l):
"""Returns a list of lenghts of consecutive equal numbers as list.
Example: [1,2,3,4,4,4,3,3] ==> [1,1,1,3,2]"""
if not isinstance(l,list):
return None
def count():
"""Counts equal elements, yields each count"""
# set the first elem as current
curr = [l[0]]
# for the rest of elements
for elem in l[1:]:
if elem == curr[-1]:
# append as long as the element is same as last one in curr
curr.append(elem)
else:
# yield the number
yield len(curr)
# reset curr to count the new ones
curr = [elem]
# yield last group
yield len(curr)
# get all yields and return them as list
return list(count())
def using_groupby(l):
"""Uses itertools.groupby and a list comp to get the lenghts."""
from itertools import groupby
grp = groupby(l) # this groups by the elems themselfs
# count the grouped items and return as list
return [ sum(1 for _ in items) for g,items in grp]
测试:
A = [1,1,2,2]
B = [3,3,3,3,7,7,7]
C = [1,1,2,2,2,1,1,1,1,1,6,6]
for e in [A,B,C]:
print(count_em(e), using_groupby(e))
输出:
# count_em using_groupby Input
[2, 2] [2, 2] # [1,1,2,2]
[4, 3] [4, 3] # [3,3,3,3,7,7,7]
[2, 3, 5, 2] [2, 3, 5, 2] # [1,1,2,2,2,1,1,1,1,1,6,6]