有什么办法可以缩短这段代码?我需要我的任务

import re
path='C:\\Users\\Matko\\Desktop\\namirnice.txt'
def cijene():
    global namirnice
    namirnice={}
    f=open(path,'r')
    for i in f:
        i=i.replace('\n','')
        namirnice[i]=(input(i+' '))
    f.close()
    f=open(path,'w')    
    for i in namirnice:
        f.writelines(i+' '+str(namirnice[i])+'\n')
    f.close()
def sort(how):
    poredak=[]
    for i in namirnice:
        if how=='po abecedi':
            poredak.append(i+' '+str(namirnice[i]))
        if how=='po cijeni':
            poredak.append(str(namirnice[i])+' '+i)
    if how=='po cijeni':
        poredak.sort(key=lambda i: float(re.split('\s',i)[0]))
    else: poredak.sort()
    for i in poredak:
        print(i)
评论