• 小作业学习


    '''
    文件a.txt内容:每一行内容分别为商品名字,价钱,个数。
    apple 10 3
    tesla 100000 1
    mac 3000 2
    lenovo 30000 3
    chicken 10 3

    通过代码,将其构建成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。
    '''

    '''
    strip用法:
    Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
    注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

    例子:
    str = "00000003210Runoob01230000000";
    print str.strip( '0' ); # 去除首尾字符 0 有几个0就去几个0

    str2 = "   Runoob      ";   # 去除首尾空格
    print str2.strip();
    
    str = "123abcrunoob321"
    print (str.strip( '12' ))  # 字符序列为 12  自定义取头尾的字符串
    

    '''

    '''
    split用法:(返回的是列表,请注意是列表)
    Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
    str.split(str="", num=string.count(str))
    参数:
    str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。
    num -- 分割次数。默认为 -1, 即分隔所有。
    例子:
    str = "Line1-abcdef Line2-abc Line4-abcd";
    print str.split( ); # 以空格为分隔符,包含
    print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个

    # 第二个参数为 1,返回两个参数列表
    x = txt.split("#", 2)
    print(x)
    

    '''

    li = []
    with open('作业',encoding='utf-8',mode='r') as file:
    for line in file:
    dic = {}
    line = line.strip() #apple 10 3 去掉空格 之类的东西s
    line_list = line.split() #['apple', '10', '3']
    dic['name'] = line_list[0]
    dic['apple'] = line_list[1]
    dic['amount'] = int(line_list[2])
    print(dic)

    感谢:https://www.runoob.com/python/att-string-strip.html

  • 相关阅读:
    HDU 1203 I NEED A OFFER!(0-1背包)
    poj3624 Charm Bracelet(0-1背包 滚动数组)
    Contest1803
    2019 Multi-University Training Contest 3
    Circle and Points
    分治算法应用-最近点对的最小距离-hdu 1007 Quoit Design
    2019年第二阶段我要变强个人训练赛第十七场
    2019牛客暑期多校训练营(第四场)
    2019牛客暑期多校训练营(第三场)
    2019 Multi-University Training Contest 2
  • 原文地址:https://www.cnblogs.com/hsyw/p/13587173.html
Copyright © 2020-2023  润新知