如何计算defaultdict(python)中元组中的唯一键元素?

时间:2017-10-29 21:15:31

标签: python list tuples defaultdict

我有以下字典,键是元组:

 defaultdict(<class 'float'>, {('abc', 'xyz'): 1.0, ('abc', 'def'):
 3.0, ('abc', 'pqr'): 1.0, ('pqr', 'xyz'): 1.0, ('pqr', 'def'): 1.0})

如何计算第一个关键元素和第二个关键元素, 所以我可以得到:

defaultdict(<class 'float'>, {'abc': 3.0, 'pqr': 3.0})

defaultdict(<class 'float'>, {'xyz': 2.0, 'def': 2.0, 'pqr': 1.0})

我忽略了原始字典中的值,只计算了唯一键(分别为第一个和第二个)。

我想做类似以下的事情,但我收到错误“'tuple'对象没有属性'items'”:

first_key_list =[j[0][0] for i in dictionary for j in i.items()]
new_dict = collections.defaultdict(float)
for i in first_key_list:
    new_dict[i] += 1

2 个答案:

答案 0 :(得分:2)

您采用自己的方法走在正确的轨道上。但是,如果你想数数,我建议使用from collections import Counter c1 = Counter(k[0] for k in d.keys()) c2 = Counter(k[1] for k in d.keys()) 对象。

d.keys()

说实话,c1 Counter({'abc': 3, 'pqr': 2}) c2 Counter({'def': 2, 'pqr': 1, 'xyz': 2}) 在这里是多余的,因为默认情况下迭代在键上。

{{1}}

答案 1 :(得分:1)

public class Program { static void Main() { var builder = new ContainerBuilder(); builder.RegisterType<MyMessageHandler>().As<IMessageHandler>(); builder.RegisterType<Functions>() .InstancePerDependency(); var host = new JobHost(new JobHostConfiguration { JobActivator = new AutofacJobActivator(builder.Build()) }); host.RunAndBlock(); } } public class AutofacJobActivator : IJobActivator { private readonly IContainer _container; public AutofacJobActivator(IContainer container) { _container = container; } public T CreateInstance<T>() { return _container.Resolve<T>(); } } public class Functions { private IMessageHandler _myService; //You can use Dependency Injection if you want to. public Functions(IMessageHandler myService) { _myService = myService; } // This function will get triggered/executed when a new message is written // on an Azure Queue called queue. public async Task ProcessQueueMessage1( [QueueTrigger("test1")] CloudQueueMessage message, IBinder binder) { _myService.HandleMessage(message.AsString); Console.WriteLine("ProcessQueueMessage1 was run"); await Task.CompletedTask; } public async Task ProcessQueueMessage2( [QueueTrigger("test2")] CloudQueueMessage message, IBinder binder) { _myService.HandleMessage(message.AsString); Console.WriteLine("ProcessQueueMessage2 was run"); await Task.CompletedTask; } } 无法正常工作,因为外部循环会产生字典键(元组),而for i in dictionary for j in i.items()不适用于items

无论如何,您似乎忽略了词典的价值观。只需在密钥的第一部分使用tuples

collections.Counter

结果:

d = {('abc', 'xyz'): 1.0, ('abc', 'def'):
 3.0, ('abc', 'pqr'): 1.0, ('pqr', 'xyz'): 1.0, ('pqr', 'def'): 1.0}

import collections

d1 = collections.Counter(k[0] for k in d)

print(d1)

如果你想要浮点数,我建议你在计算后转换为float 以避免浮点不准确:

Counter({'abc': 3, 'pqr': 2})

或一行:

{k:float(v) for k,v in d1.items()}

将密钥保持为元组:

d1 = {k:float(v) for k,v in collections.Counter(k[0] for k in d).items()}

对于第二部分,只需使用d1 = {(k,):float(v) for k,v in collections.Counter(k[0] for k in d).items()}