Python:While Statement = Statement打印关联值 [英] Python: While Statement = Statement Print associated Values

查看:169
本文介绍了Python:While Statement = Statement打印关联值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我目前有一个具有复合键的字典。在这个字典中有这些键的多次发生。 (密钥用逗号分隔):

 (A,B),(A,C),(A,B) ,(A,D),(C,A),(A,B),(C,A),(C,B),(C,B)
p $ p>

我已经有了一些总结出现的独特事件,并计算出与我相似的打印输出的重复项:


$ b $计数 4 (A,B)(A,B) C),计数为 2 (B,C) 6 等。



我想知道如何编写一个循环,给我以下内容: / p>

打印第一部分键的首次出现及其不相关的值和计数。



名称: A:

 类型计数

B 4
C 2

总计6

名称:B:

 类型计数
A 3
B 2
C 3
总计8
pre>

我知道我需要创建一个循环,其中 fir st语句=第一个语句并执行以下操作,但没有真正的想法如何接近/编码这个。

解决方案

这是一个稍微缓慢的算法,可以完成:

  def convert(myDict):
keys = myDict.keys()
answer = collections.defaultdict(dict)
键中的键:$对于k中的k,在k中的k中,如果k.startswith(key [0]),则为k):
answer [key [0]] [k [1]] = myDict [k]
返回答案

最后,我想你以后是一个 trie


In Python I currently have a Dictionary with a composite Key. In this dictionary there are multiple occurences of these keys. (The keys are comma-separated):

(A,B), (A,C), (A,B), (A,D), (C,A), (A,B), (C,A), (C,B), (C,B)

I already have something that totals the unique occurrences and counts the duplicates which gives me a print-out similar to this:

(A,B) with a count of 4, (A,C) with a count of 2, (B,C) with a count of 6, etc.

I would like to know how to code a loop that would give me the following:

Print out the first occurance of the first part of the key and its associtated values and counts.

Name: A:

Type Count

B     4
C     2

Total  6

Name: B:

Type Count
A    3
B    2
C    3
Total 8

I know I need to create a loop where the first statement = the first statement and do the following, but have no real idea how to approach/code this.

解决方案

Here's a slightly slow algorithm that'll get it done:

def convert(myDict):
    keys = myDict.keys()
    answer = collections.defaultdict(dict)
    for key in keys:
        for k in [k for k in keys if k.startswith(key[0])]:
            answer[key[0]][k[1]] = myDict[k]
    return answer

Ultimately, I think what you're after is a trie

这篇关于Python:While Statement = Statement打印关联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆