遍历词典的问题

时间:2014-11-27 23:38:49

标签: python dictionary

a_list = [45, 90, 30, 33, 34, 64, 34, 28, 72, 20]

def sort_by_digit(a_list):

list_0 = []
list_1 = []
list_2 = []
list_3 = []
list_4 = []
list_5 = []
list_6 = []
list_7 = []
list_8 = []
list_9 = []


digit_dic = dict()
x = 0
for i in a_list:
    val = a_list[x] % 10

    x +=1

    if val == 0:
        list_0.append(i)

    elif val == 1:
        list_1.append(i)

    elif val == 2:
        list_2.append(i)

    elif val == 3:
        list_3.append(i)

    elif val == 4:
        list_4.append(i)

    elif val == 5:
        list_5.append(i)

    elif val == 6:
        list_6.append(i)

    elif val ==7:
        list_7.append(i)

    elif val == 8:
        list_8.append(i)

    elif val == 9:
        list_9.append(i)



if len(list_0) != 0:
    digit_dic[0] = list_0

if len(list_1) != 0:
    digit_dic[1] = list_1

if len(list_2) != 0:
    digit_dic[2] = list_2

if len(list_3) != 0:
    digit_dic[3] = list_3

if len(list_4) != 0:
    digit_dic[4] = list_4

if len(list_5) != 0:
    digit_dic[5] = list_5

if len(list_6) != 0:
    digit_dic[6] = list_6

if len(list_7) != 0:
    digit_dic[7] = list_7

if len(list_8) != 0:
    digit_dic[8] = list_8

if len(list_9) != 0:
    digit_dic[9] = list_9

print digit_dic

return digit_dic


def chart(dictionary):

   x = 0

   for i in a_list:
       if x not in dictionary:
           x += 1 
   else:
       number_of_hashes = len(dictionary[x])
       print x, number_of_hashes * '#'
       x += 1     

chart(sort_by_digit(a_list))       

我必须编写一个程序,按照最后一个数字对随机列表进行排序,并将它们放在一个字典中,最后一个数字作为键。之后我必须编写一个程序来打印键值对的长度,所以对于axample我将得到输出

0 ### 2# 3# 4 ### 5# 8#

然而我被困在0 ###并且我不知道我做错了什么以及为什么其他输出没有出现!请帮助,我的代码的任何其他评论都非常欢迎!非常感谢你!

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

#!/usr/local/cpython-3.4/bin/python

import pprint
import collections

def main():
    a_list = [45, 90, 30, 33, 34, 64, 34, 28, 72, 20]
    dict_ = collections.defaultdict(list)
    for element in a_list:
        val = element % 10
        dict_[val].append(element)
    pprint.pprint(dict_)

main()

答案 1 :(得分:1)

我可以尝试这种方式:

#!/usr/bin/python

dic = dict()

lis = [45, 90, 30, 33, 34, 64, 34, 28, 72, 20]

for dig in lis:
    key = str(dig)[1]
    dic.setdefault(key, [])
    dic[key].append(dig)

for k in sorted(dic.keys()):
    print k, '#'*len(dic[k]),

输出:

0 ### 2 # 3 # 4 ### 5 # 8 #