python 两个数组多次for循环实现和使用词典和sorted来实现

合并表记录

http://www.nowcoder.com/questionTerminal/de044e89123f4a7482bd2b214a685201

第一次做出来的答案,算法比较耗时。耗时2s。没通过。

方法1:比较差的做法。

while True:
    try:
        num = input()
        dict_index = []
        dict_value = []
        length = int(num)
        for i in range(int(num)):
            dict_str = input()
            dict_list = dict_str.split(' ')
            dict_index.append( int(dict_list[0]))
            dict_value.append(int(dict_list[1]))

        for i in range(int(num)-1):
            for j in range(i+1,int(length)):
                if dict_index[i] == dict_index[j]:
                    dict_value[i] = dict_value[i]+ dict_value[j]
                    for k in range(j,int(length)-1):
                        dict_value[k] = dict_value[k+1]
                        dict_index[k] = dict_index[k+1]
                    #pdb.set_trace()
                    length = length -1
                    break
        x_min = dict_index[0]
        for i in range(length-1):
            for j in range(i+1,length):
                if dict_index[i]>dict_index[j]:
                    temp =dict_index[i]
                    dict_index[i] = dict_index[j]
                    dict_index[j] = temp

                    temp = dict_value[i]
                    dict_value[i] = dict_value[j]
                    dict_value[j] = dict_value[i]
        for i in range(length):
            print(str(dict_index[i]) + ' ' + str(dict_value[i]))
    except:
        pass

方法2:使用map来生成词典。使用sorted来给字典排序

while True:
    try:
        n = int(input())
        dic = {}
        for i in range(n):
            x, y = map(int, input().split(' '))
            if x in dic:
                dic[x] = dic[x] + y
            else:
                dic[x] = y

        #方法1:
        dic = sorted(dic.items(), key = lambda item:item[0])  #dic.items()以列表形式返回dict
        for i in dic:
            #print(i[0], i[1])
            print('{} {}'.format(i[0], i[1]))
        #方法2:
        #d = sorted(dic)
        #for i in d:
            #print(i, dic[i])


    except:
        break
全部评论

相关推荐

1 1 评论
分享
牛客网
牛客企业服务