首页 文章

Python字典打印首次出现

提问于
浏览
2

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

第一个值是数字,第二个值(A或B)表示文本值,数字是它们出现在此字典的原始列表列表中的次数 .

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

键入:111文本计数

A     4
       B    10

      Total: 14

键入:112文本计数

A      3

     Total:   3

我知道当与If语句结合使用时,我需要使用某种while循环 . 根据我迄今为止所研究的内容(与我迄今为止为Python所教授的内容相关),我需要使用if语句编写循环以仅打印我想要打印的内容 . 所以我需要在它们第一次出现时打印新的数字值,而不是它们出现的第二个(或第三个或第四个等)时间 . 我假设部分执行此操作,我将它们放在变量中,然后将它们与当前值进行比较 . 如果它们是相同的,我不打印它们,但如果它们不同,我打印旧数值的“总数”,将其添加到总数中,然后打印新的数值 .

5 回答

  • 3

    我写了一个简单的函数来打印你想要的东西 . 它需要字典作为第一个参数,类型作为第二个int(例如 fancy_print({'111, A': 4, '112, A': 3,'111, B': 10}, 111) ):

    def fancy_print(d, typ):
        res=[]
        for k in d:
            kp=[q.strip() for q in k.split(',')]
            if int(kp[0])==typ:
                res.append((kp[1],d[k]))
        res.sort()
        print('\tType: %d Text Count' % typ)
        for t,n in res:
            print('\t%s\t%2d' % (t, n))
        print()
        print('\tTotal:\t%2d' % sum([n[1] for n in res]))
    
  • 5

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

    考虑一个dict中的dicts示例:

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

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

    for key in data['111']:
        print "%s\t%s" % (key, data['111'][key])
    

    通过组合两个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
    
  • 0

    您可以使用元组作为键 . 而不是 '111, A' 试试 ('111', 'A')

    它允许您轻松遍历字典,查找与第一个或第二个键值匹配的字典 . 就像你拥有的一样,除了更改密钥:

    for row in lists: 
        key = (row[0], row[1])
        if key in dictionary: 
            dictionary[key] += 1 
        else: 
            dictionary[key] = 1
    
    #gives
    dictionary = {('111', 'A'): 4, ('111', 'B'):10, ('112', 'A'):4}
    

    现在,你是完全正确的:你需要一个变量来存储总数,你需要循环遍历字典,你需要在循环中使用条件语句 . 你究竟在问什么?

    您可以像这样遍历字典:

    for k in d:
        print k, d[k]
    

    如果保留字符串键,则需要从每个键中提取两个值,您可以使用 split . (如果使用元组,则无需执行此步骤):

    #with string keys
    key_1, key_2 = k.split(',')
    

    您需要测试第一个键值是否与所需的数字匹配,然后您要打印字母和值d [k],并更新总变量:

    if key_1 == desired:
        print key_2, d[k]
        total += d[k]
    

    所以你可以把它放在一起,在这样的函数中:

    def f(d, desired):
        total = 0
        for k in d:
            key_1, key_2 = k.split(',')
            if key_1 == desired:
                print key_2, d[k]
                total += d[k]
        print 'total', total
    

    如果使用元组而不是键,则可以删除拆分步骤,只需使用k [0]和k [1]得到两个值:

    def f(d, desired):
        total = 0
        for k in d:
            if k[1] == desired:
                print k[0], d[k]
                total += d[k]
    
        print 'total', 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]
    

    输出:

    111
         B 10
         A 4
    112
         A 3
    

    这需要非常小的修改才能到达您需要的位置 .

    EDIT :“解释 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 中的键)然后迭代,而 for k in myDict 直接遍历 myDict 中的所有键

  • 2

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

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

    然后你可以轻松打印字典:

    for k,v in d.items():
       print "Type: {0}\t Text Count".format(k)
       for item in v:
           print "\t\t{0}  {1}".format(*v)
    

    要将您的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))
    

相关问题