Python字典首次打印

2024-06-17 10:35:48 发布

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

在Python中,我当前有一个字典(它有一个来自列表中列表的复合键),当我打印它时,它看起来类似于以下内容:

第一个值是一个数字,第二个值(a或B)是一个文本值,这些数字是它们出现在源于此词典的原始列表中的次数。在

我需要的是一种以以下格式打印出数据的方法。对于数字值在字典中唯一出现的情况(即在本例中是第一个和第三个值),打印出相关联的文本值及其计数。所以看起来像

类型:111文本计数

       A     4
       B    10

      Total: 14

类型:112文本计数

^{pr2}$

我知道我需要在与If语句结合时使用某种while循环。根据我目前所研究的内容(与我目前所学的Python相关),我需要用if语句编写循环来只打印我想打印的内容。所以我需要在第一次出现时打印新的数值,而不是第二次(或第三次或第四次,等等)打印它们。我假设部分地这样做,我把它们放在一个变量中,然后将它们与当前值进行比较。如果它们是相同的,我不会打印它们,但是如果它们不同,我会打印旧数值的“总计”,将其添加到总数值中,然后打印新的数值。在


Tags: 数据方法文本类型内容列表字典格式
3条回答

在我看来,更好的数据结构应该是:

{111:[('A', 4),('B',10)], 112:[('A': 3)]}

然后您可以轻松地打印dict:

^{pr2}$

要将您的dict转换为这种形式,我将使用defaultdict

from collections import defaultdict
d = defaultdict(list)
for k,v in yourdict.items():
    new_key,value0 = (x.strip() for x in k.split(','))
    d[int(new_key)].append((value0,v))

我将使用对象的层次结构而不是一个平面字典,比如dict中的dict,dict中的元组,等等

以dict中的dict为例:

data = { 
    '111': {
        'A': 4,
        'B': 10,
    },
    '112': {
        'A': 3
    },
}

现在您可以更轻松地访问内容。例如“111”中的显示属性:

^{pr2}$

通过组合两个for循环,可以稍微简单地创建所需的输出:

for datatype in data:
    print("Type: %s Text Count" % datatype)
    items = data[datatype]
    total = 0
    for key in items:
        print "%s\t%s" % (key, items[key])
        total += items[key]
    print("Total:\t%s\n" % total)

使用给定数据运行上述操作将产生以下输出:

Type: 111 Text Count
A       4
B       10
Total:  14

Type: 112 Text Count
A       3
Total:  3

既然这是家庭作业,我给你的代码几乎就是答案:

myDict = {'111, A': 4, '112, A': 3, '111, B': 10} # input

# keep track of the first half of the composite keys that you've already handled
# This is used to avoid redundant printing
done = set()

for key in myDict:
    # first half of your composite key (eg. '111')
    # I'll be using '111' to explain the rest of the code
    prefix = key.split(',')[0]

    if prefix not in done: # if you haven't already printed out the stuff for '111'
        print prefix # print '111'
        done.add(prefix) # add '111' to done, so that you don't print it out again

        # for all keys in myDict that are of the form "111,X" where X can be anything (e.g. A)
        for k in [k for k in myDict if k.split(',')[0]==prefix]:

            # print a <tab> and the suffix (in our example, "A") and the count value (in myDict, this value is 4)
            print '\t', k.split(',')[1], myDict[k]

输出:

^{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]。此列表理解可以改写为:

myList = []
for k in myDict:
    if k.split(',')[0]==prefix:
        myList.append(k)

然后你就可以了

for k in myList:

关于for k in myDict有一些话要说。当您像这样迭代一个dict时,您只迭代键。这与说for k in myDict.keys()相同。区别在于myDict.keys()返回一个新的列表(属于myDict中的键),然后对其进行迭代,而{}则直接迭代{}中的所有键

相关问题 更多 >