从元组组合中获取顶部计数

2024-09-29 21:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表。每个元组是一个键-值对,其中键是一个数字,值是一个字符串。对于每个键,我需要以列表形式返回前两个字符及其计数。你知道吗

例如,给定列表

[(1, "aabbc"), (1, "babdea"), (2, "aabacc"), (2, "acdad")]

键为1和2,值为

"aabbc", "babdea", ..., "acdaad"

元组可以转换成

(1, {"a":2, "b":2, "c":1}),(1,{"a":2, "b":2, "d":1,"e":1})...(2,{"a":2, "c":1, "d":2})

对于键1,组合元组将是

(1,{"a":4, "b":4, "c":1, "d":1,"e":1})

所以最重要的两个人物是

[("a",4),("b",4)]

每个键都会重复这个过程

我能够得到我想要的输出,但我正在寻找一个更好的解决方案

from collections import Counter
l=[(x[0],list(x[1])) for x in [(1, "aabbc"), (1, "babdea"), (2, "aabacc"), (2, "acdad")]]
l2=[(y[0],Counter(y[1])) for y in l]

l3=[(x[0][1],x[1][1]) for x in it.combinations(l2,2) if x[0][0]==x[1][0]  ]

l4=[]
for t,y in l3:
    d={}
    l5=list(set(t.keys()).union(y.keys()))
    for i in l5:
        d[i]=t[i]+y[i]
    d_sort=sorted(d.items(), key=lambda x: x[1], reverse=True)[:2]

    l4.append(d_sort)


print l4
[[('a', 4), ('b', 4)], [('a', 5), ('c', 3)]]

Tags: in列表forcounterkeyslist元组l3
3条回答

您还可以使用相同的键连接反字符串,然后计算字符数并提取两个最常见的字符:

import collections

data = [(1, "aabbc"), (1, "babdea"), (2, "aabacc"), (2, "acdad")]

groups = collections.defaultdict(str)
for i, s in data: 
   groups[i] += s 

print([collections.Counter(string).most_common(2)
       for string in groups.values()])

您将得到:

[[('a', 4), ('b', 4)], [('a', 5), ('c', 3)]]

我会使用一个defaultdict来保存Counter,它在遍历元组列表时被更新:

>>> from collections import Counter, defaultdict
>>> data = [(1, "aabbc"), (1, "babdea"), (2, "aabacc"), (2, "acdad")]
>>> 
>>> result = defaultdict(Counter)
>>> for num, letters in data:
...     result[num].update(letters)
... 
>>> result
defaultdict(<class 'collections.Counter'>, {1: Counter({'a': 4, 'b': 4, 'c': 1, 'e': 1, 'd': 1}), 2: Counter({'a': 5, 'c': 3, 'd': 2, 'b': 1})})

为了获得两个最常见的字母,Counter对象有一个有用的most_common方法。你知道吗

>>> {k:v.most_common(2) for k,v in result.items()}
{1: [('a', 4), ('b', 4)], 2: [('a', 5), ('c', 3)]}

不是更好,而是更短:

from itertools import groupby
from collections import Counter


lst = [(1, "aabbc"), (1, "babdea"), (2, "aabacc"), (2, "acdad")]

[Counter(''.join(list(zip(*y[1]))[1])).most_common(2) for y in groupby(lst, key=lambda x: x[0])]

# [[('a', 4), ('b', 4)], [('a', 5), ('c', 3)]]

我希望这有帮助。你知道吗

相关问题 更多 >

    热门问题