在Python中,我当前有一个字典(它有一个来自列表中列表的复合键),当我打印它时,它看起来类似于以下内容:
第一个值是一个数字,第二个值(a或B)是一个文本值,这些数字是它们出现在源于此词典的原始列表中的次数。在
我需要的是一种以以下格式打印出数据的方法。对于数字值在字典中唯一出现的情况(即在本例中是第一个和第三个值),打印出相关联的文本值及其计数。所以看起来像
类型:111文本计数
A 4
B 10
Total: 14
类型:112文本计数
^{pr2}$我知道我需要在与If语句结合时使用某种while循环。根据我目前所研究的内容(与我目前所学的Python相关),我需要用if语句编写循环来只打印我想打印的内容。所以我需要在第一次出现时打印新的数值,而不是第二次(或第三次或第四次,等等)打印它们。我假设部分地这样做,我把它们放在一个变量中,然后将它们与当前值进行比较。如果它们是相同的,我不会打印它们,但是如果它们不同,我会打印旧数值的“总计”,将其添加到总数值中,然后打印新的数值。在
在我看来,更好的数据结构应该是:
然后您可以轻松地打印dict:
^{pr2}$要将您的dict转换为这种形式,我将使用
defaultdict
:我将使用对象的层次结构而不是一个平面字典,比如dict中的dict,dict中的元组,等等
以dict中的dict为例:
现在您可以更轻松地访问内容。例如“111”中的显示属性:
^{pr2}$通过组合两个for循环,可以稍微简单地创建所需的输出:
使用给定数据运行上述操作将产生以下输出:
既然这是家庭作业,我给你的代码几乎就是答案:
输出:
^{pr2}$这需要非常小的修改才能让你到达你需要的地方。在
编辑:“解释
for k in [k for k in myDict if k.split(',')[0]==prefix]:
的工作原理”这句话有两个部分。第一个是一个简单的for循环(
for k in …
),它与往常一样工作。第二个是列表理解[k for k in myDict if k.split(',')[0]==prefix]
。此列表理解可以改写为:然后你就可以了
关于}则直接迭代{}中的所有键
for k in myDict
有一些话要说。当您像这样迭代一个dict
时,您只迭代键。这与说for k in myDict.keys()
相同。区别在于myDict.keys()
返回一个新的列表(属于myDict
中的键),然后对其进行迭代,而{相关问题 更多 >
编程相关推荐