小杨学Python (二) 基本数据结构

本节回顾:
---- list有序,可增删改查,tuple是只读列表,不能修改,有序
----dict是无序,可增删改查
----string,可查,但不能修改,因为改变的字符只是产生一个新内容把之前的覆盖了

1.关于python “”.join() 出错TypeError: sequence item 0: expected string
需要将list转为string
在list转string时,如果list元素不为string时需要转换为string
2. list的方法
几个比较混淆的
a=[1,2,3,4]
print(a[:]) 结果 [1,2,3,4]
print(a[1:]) 结果 [2,3,4]
print(a[1:3]) 结果 [2,3] 注意[]永远顾头不顾尾
print(a[-2:]) 结果 [3,4] 注意 1,2,3,4对应 0,1,2,3 或者 -4,-3,-2,-1
print(a[-3:-1]) 结果 [2,3]

names = ["a","b","c","d"]
names.append("e") # 追加到尾
names.insert(1,"x") # 插入位置 下标为1
names[2]="y" # 修改

# print(names[0],names[1])
# print(names[1:3]) # 切片 顾头不顾尾
# print(names[len(names)-1]) # 取最后以为
# print(names[-1]) # 从右边开始数
# print(names[-1:-3])
# print(names[-3:-1]) # 不包含最后一个
# print(names[-2:]) # 包含尾
# print(names[0:3])

#delete
#names.remove("a")
#del names[1]
#names.pop() # 默认删最后一个
#names.pop(1)
print (names)
print(names.index("y"))
names.reverse()
names.sort() # ascll码排序
names2 = [1,2,3]
names.extend(names2)
print(names,names2)
print(names[0:-1:2]) # 2为步长

3.string的方法

name = "my  name is {name} and i am {year}'s old"
print(name.capitalize())
print(name.count("a"))
print(name.center(50,"-")) # 中心
print(name.endswith("ex"))
#print(name.expandtabs(tabsize=30))
print(name.find("name")) # 返回index
print(name[name.find("name"):])
print(name.format(name='alex',year='22'))
print(name.format_map({'name':'alex','year':'22'})) # 只能加dict
print('ab23'.isalnum()) # 包含阿拉伯数据字或阿拉伯字符
print('ab23'.isalpha()) # 包含字符
print('1.23'.isdecimal())
print('1A'.isdigit())
print('a 1A'.isidentifier()) # 判断是不是一个合法的标识符
print('33.33'.isnumeric())
print('+'.join(['1','2','3']))
print(name.ljust(50,'*')) # 不够用*号表示
print(name.rjust(50,"*"))
print('    alex\n'.strip()) # 去首尾空格  strip('a')去除首字符为a
p = str.maketrans("abcdefli","123$@456")
print("alex li".translate(p))
print('alex li'.replace('l','L'))
# print('alex li'.replace('l','L',1))
# print('alex li'.rfind('l'))
# print('1+2+3+4'.split('+')) # 分割
# print('1+2\n+3+4'.splitlines()) # 分割
# print('Alex LI'.swapcase())
# print('yang hao rna'.title())
# print('alex li'.zfill(50))

4.dict的方法

info = {
    'stu1':'y',
    'stu2':'a',
    'stu3':'c',
}

print(info)
#print(info['stu1'])
info['stu1']='z'
print(info)
del info['stu1']
#info.pop('stu1')
#info.popitem() # 随机删除
print(info.get('stu2'))
print('stu1' in info)
'''
c = dict.fromkeys([6,7,8],[1,{"name":"alex"},444])
#print(info.items()) #dict转list

c[7][1]['name']='jack' # 三个共享一个地址'''

for i in info:
    print(i,info[i])

print(info.items()) #dict转list
for k,v in info.items():
    print(k,v )

5.day2作业购物车优化
需求:
(1)用户界面
:用户输入钱包余额,从文件读到商品信息。
:通过商品下标选择商品,显示余额并使用发光字体
:将购物车信息、余额写入文件

用户入口

#!/usr/bin/env python
# coding:utf-8
# Author:Yang
product_list=[]
with open("F:/homeworkday2.txt") as f:
    for line in f:
        product_list.append(list(line.strip('\n').split(',')))
shopping_list = []
with open("F:/homeworkday2_spl.txt") as f:
    for line in f:
        shopping_list.append(list(line.strip('\n').strip(',')))
print("用户入口".center(40,"-"))
salary = (input("please input your salary:"))
if salary.isdigit():
    salary=int(salary)
    while True:
        #for item in product_list:
         for index,item in enumerate(product_list):
            #print(product_list.index(item),item)
            print(index,item)
         user_choice = input("选择要买吗>>>:")
         if user_choice.isdigit():
             user_choice=int(user_choice)
             if user_choice < len(product_list) and user_choice >=0:
                 p_item = product_list[user_choice]
                 p_item[1]=int(p_item[1])
                 if p_item[1] <= salary: # 买得起
                     shopping_list.append(p_item)
                     salary -=p_item[1]
                     print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" % (p_item,salary))
                 else:
                     print("\033[41:1m你的余额只剩[%s]\033[0m" % salary)
             else:
                 print("product code [%s] is not exist!",user_choice)

         elif user_choice == 'q':
             with open("F:/homeworkday2_spl.txt","+w") as f:
               print("-------shopping list------")
               for index,item in enumerate(shopping_list):
                print(index,item)
                shopping_list_str="\n".join(str(s) for s in shopping_list)
                wirte_str=((shopping_list_str.replace("[","")).replace("]","")).replace("'","")
                f.write(wirte_str)
             with open("F:/homeworkday2_sly.txt","+a") as f:
               print("Your current balance:",salary)
               f.write("Your current balance:"+str(salary)+'\n')

               exit()
         else:
             print("invalid option")


(2)商家界面
:修改商品,写入文件
:添加商品,写入文件

商家入口

#!/usr/bin/env python
# coding:utf-8
# Author:Yang
#
# product = input("please input a product:")
# price = input("please input the price of product:")
product_list = []
with open("F:/homeworkday2.txt") as f:
    for line in f:
        product_list.append(list(line.strip('\n').split(',')))
#print(product_list)
print("商家入口".center(40,"-"))
print("1.查看商品列表\n2.添加商品\n3.修改商品")
choice = input("pleace choose an operation:")

if choice.isdigit():
    if choice == "1": # 选择1得到商品列表
       for index,item in enumerate(product_list):
         print(index,item)
    elif choice == "2": # 选择2进行新增商品
        product_add = input("please input a product:")
        price_add = input("please input the price of the %s:"%(product_add))
        # add_list=[product_add,price_add]
        # product_list.append(add_list)
        with open('F:/homeworkday2.txt',"a+") as f:
            f.write('\n'+product_add+','+price_add)
    elif choice == "3": # 选择3进行修改商品
        for index, item in enumerate(product_list):
            print(index, item)
        product_index = int(input("please input the index of product:")) # 输入要修改的商品编号
        print("1.alter product name\n2.alter product price") # 选择修改商品名或者商品价格
        product_alter = input("please input the choice:")
        if product_alter == "1":
            product_name = (input("please input the new name of product:"))
            product_list[product_index][0]=product_name
        elif product_alter == "2":
            product_price = input("please input the new price of product:")
            product_list[product_index][1]=product_price
        else:
            print("invoid operation")

        product_list_str="\n".join(str(s) for s in product_list) # 商品列表list转str
        write_str=(product_list_str.replace('[','')).replace(']','').replace("'","").replace(" ","") # 分割字符串
        with open("F:/homeworkday2.txt","+w") as f:
            f.write(write_str)
    else:
        print("invoid operation")
else:
        print("invoid operation")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值