继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

python的字典与列表学习

临摹微笑
关注TA
已关注
手记 162
粉丝 32
获赞 169
#字典练习
def print_dict():
    contect_file = 'contect_list.txt'
    f = file(contect_file)  #读取
    contect_dic = {}
    for line in f.readlines():
        name = line.split()[1]
        contect_dic[name] = line  #是修改也是添加
    #print contect_dic  #调试输出
    '''
    for n,v in contect_dic.items():
         print "%s \t%s" % (n,v),  #调试输出看
         '''
    while True:
        inputvales = raw_input("Please input the staff name:").strip()
        if len(inputvales) == 0:
            continue
        if contect_dic.has_key(inputvales):
            print "%s \t"% contect_dic[inputvales]
        else:
            print 'Sorry ,no staff name find!'
#print_dict()
#列表练习
def print_show():
    f = file('shop.txt')
    products = []
    prices = [0]
    shops_list = [0]
    for line in f.readlines():
        new_line = line.split()
        print new_line[0]
        products.append(new_line[0])
        prices.append(int(new_line[1])) #如果不改变类型,这样加进入是str类型
    #print products
    #print prices
    salary = int(raw_input("please input your salary:"))
    while True:
        print "welcome ,things you can buy as below:"
        for p in products:
            p_index = products.index(p)
            p_price = prices[p_index]   #通过索引查找对应值
            print p,p_index,p_price    #验证结果
        choice = raw_input('Please input what your want to buy:')
        f_choice = choice.strip()
        if f_choice in products:
            print 'Yes ,it is in list!'
            f_index = products.index(f_choice)
            f_price = prices[f_index]
            # print f_price  ,type(f_price) #调试
            if salary >= f_price:
                print "Congrautations,added %s to shop list "% f_choice
                shops_list.append(f_choice)
                salary = salary - f_price
                print "Now you have %d left !keep buying!" % salary,
            else:
                if salary < min(prices):
                    print "Soory ,your can not buy anththing !bye!\n"
                    print "you have bought :",shops_list
                    sys.exit()
                else:
                    print "Sorry ,money is not enough to buy %s ,please tyr another one!"% f_choice
        else:
            print 'Sorry ,%s  not in the list ,pleass try another one :'% f_choice
#文件操作
def open_file():
    #f = open('contanct_list.txt','r+')
    with open('data.txt','r+') as f:
        old = f.read()
        f.seek(36)       #单行修改
        f.write("liwen is back is good")
#open_file()
def open_file_01():
    for line in fileinput.input("data.txt",backup="bak",inplace=1): #back 备份
        line = line.replace('meingli','liwen is good')  #只有meingli 就 替换
        print line
#open_file_01()


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP