我有一个元组列表。每个元组是一个键-值对,其中键是一个数字,值是一个字符串。对于每个键,我需要以列表形式返回前两个字符及其计数。你知道吗
例如,给定列表
[(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)]]
您还可以使用相同的键连接反字符串,然后计算字符数并提取两个最常见的字符:
您将得到:
我会使用一个
defaultdict
来保存Counter
,它在遍历元组列表时被更新:为了获得两个最常见的字母,
Counter
对象有一个有用的most_common
方法。你知道吗不是更好,而是更短:
我希望这有帮助。你知道吗
相关问题 更多 >
编程相关推荐