python如何方便地计算列表集合中列表的频率
我有一张名单python如何方便地计算列表集合中列表的频率,python,list,counter,Python,List,Counter,我有一张名单 e.g. list_a = [[1,2,3], [2,3], [4,3,2], [2,3]] 我想把它们数成这样 [1,2,3]: 1 [2,3]: 2 [4,3,2]: 1 馆藏中有一个图书馆柜台,但不存放列表等不易损坏的元素。目前,我只是尝试使用其他间接方法,例如将列表[1,2,3]转换为字符串“1_2_3”来实现这一点。是否有其他方法可以直接启用列表上的计数?这不是最漂亮的方法,但它可以: list_a = [[1,2,3], [2,3], [4,3,2], [2,3]]
e.g. list_a = [[1,2,3], [2,3], [4,3,2], [2,3]]
我想把它们数成这样
[1,2,3]: 1
[2,3]: 2
[4,3,2]: 1
馆藏中有一个图书馆柜台,但不存放列表等不易损坏的元素。目前,我只是尝试使用其他间接方法,例如将列表[1,2,3]转换为字符串“1_2_3”来实现这一点。是否有其他方法可以直接启用列表上的计数?这不是最漂亮的方法,但它可以:
list_a = [[1,2,3], [2,3], [4,3,2], [2,3]]
counts = {}
for x in list_a:
counts.setdefault(tuple(x), list()).append(1)
for a, b in counts.items():
counts[a] = sum(b)
执行此任务的一种可能方法是使用
dict
dict
中。该值将是发生计数器occurrence\u dict={}
对于列表a中的列表:
如果(事件记录获取(str(list),False)):
发生日期[str(列表)]+=1
其他:
o当前记录[str(列表)]=1
打印(发生/记录)
使用元组而不是列表
c = Counter(tuple(item) for item in list_a)
# or
c = Counter(map(tuple, list_a))
# Counter({(2, 3): 2, (1, 2, 3): 1, (4, 3, 2): 1})
# exactly what you expected
(1, 2, 3) 1
(2, 3) 2
(4, 3, 2) 1
方式1
通过可重复列表的索引
list_a = [[1,2,3], [2,3], [4,3,2], [2,3], [1,2,3]] # just add some data
# step 1
dd = {i:v for i, v in enumerate(list_a)}
print(dd)
Out[1]:
{0: [1, 2, 3], 1: [2, 3], 2: [4, 3, 2], 3: [2, 3], 4: [1, 2, 3]}
# step 2
tpl = [tuple(x for x,y in dd.items() if y == b) for a,b in dd.items()]
print(tpl)
Out[2]:
[(0, 4), (1, 3), (2,), (1, 3), (0, 4)] # here is the tuple of indexes of matching lists
# step 3
result = {tuple(list_a[a[0]]):len(a) for a in set(tpl)}
print(result)
Out[3]:
{(4, 3, 2): 1, (2, 3): 2, (1, 2, 3): 2}
方式2
通过将嵌套列表转换为元组
{i:[tuple(a) for a in list_a].count(i) for i in [tuple(a) for a in list_a]}
Out[1]:
{(1, 2, 3): 2, (2, 3): 2, (4, 3, 2): 1}
如果列表仅包含整数,则转换为tuple和apply计数器,否则,如果元素为sortable+itertools.groupby,则进行排序。否则,只是一个嵌套的loop@DanielMesejo你还需要分类first@roganjosh你的意思是使用计数器吗?Counter(map(tuple,list_a))
给出:计数器({(1,2,3):1,(2,3):2,(4,3,2):1})
@DanielMesejo我做了。。。但是现在也许有一些事情我在看你的编辑之前不知道为什么两个循环?您只需检查该键是否已存在,然后将+=1
添加到该键,默认值为0
。然后只迭代一次,并保存大量内存,因为这是第一个想到的解决方案。正如我所说,这绝对不是其他答案所显示的最好的方法。
{i:[tuple(a) for a in list_a].count(i) for i in [tuple(a) for a in list_a]}
Out[1]:
{(1, 2, 3): 2, (2, 3): 2, (4, 3, 2): 1}