返回顶部

zhangfd

个人博客,仅供学习使用

导航

2、列表及字符串

#-*- codeing = utf-8 -*-
#@Time : 2020/6/6 20:51
#@Author : zhangfudong
#@FILE :day2.py
#@Software : PyCharm

字符串:单引号,双引号,三引号的使用

word = '字符串'
sentence = "这是一个句子"
paragraph = '''
    这是一个段落
    可以由多行组成
'''

print(word)
print(sentence)
print(paragraph)

#单引号和双引号的区别,可以互相转换使用
my_str='i\'m a student'
my_str="i\'m a student"
my_str='dda said:"I like you"'
my_str="dda said:\"I like you\""
print(my_str)

字符串连接

# 使用加好"+"使几个字符串相连接
str = "chengdu"
print(str+",你好")

# 乘号"*"表示倍数
print(str*3)

# r参数,使解析失效,不做转义,依然保留原格式
print("hello \n world")   # \n表示换行,转义
print(r"hello\n world")   ### 字母r的使用:直接输出hello\nworld,不做转义

list 列表

列表索引值以0为开始值,-1为从末尾开始的值

使用+进行拼接,*进行重复

 namelist = []  ## 定义一个空的列表

namelist=["小张","小王","小李"]
print(namelist[0],namelist[1])
print(namelist[2])

typeList=[1,"小王八"]          ### 列表中可以同时使用不同类型
print(type(typeList[0]))
print(type(typeList[1]))

for name in namelist:
    print(name)

print(len(namelist))

i=0
while i<len(namelist):
    print(namelist[i])
    i+=1

1、增加的三种方式:append、extend、insert

## 追加:[append],在list末尾追加一个元素,追加的全部当做一个元素
## 扩展:[extend],在list末尾扩展元素,将需追加的逐个加入,是多个元素
## 插入:[insert],在指定下标位置插入元素

# list列表中数据增删改查的
namelist=["小张","小王","小李"]
print("---- 追加前,名单列表的数据----")
for i in  namelist:
    print(i)

## name=input("请输入需要追加的姓名:")    ## 读入一个元素
name=["张龙","赵虎","王朝","马汉"]

## append追加:输出为嵌套数组,新追加的数组当做原数组的一个元素
namelist.append(name)               ## 在末尾追加一个元素

## extend扩展:输出原来的数组,新扩展的数组被逐个拆分为原数组的多个元素
namelist.extend(name)

## insert插入语法:insert(插入的位置下标,"插入的内容")
namelist.insert(2,"伪装者插入")
print("---- 追加后,名单列表的数据----")
for i in  namelist:
    print(i)

print(namelist)

2、删除的三种方式

### delete:删除指定位置下标的元素
### pop:删除最后一个元素
### remove:删除指定内容的元素

movieName=["加勒比海盗","黑客帝国","第一滴血","指环王","速度与激情"]
print("---- 删除前,名单列表的数据----")
print(movieName)

## del:删除指定位置下标的元素
del movieName[2]

## pop:删除最后一个元素
movieName.pop()

## 数组中可以由重复元素
remove:删除匹配内容的第一个元素,不是全部删除指定内容
movieName.remove("指环王")

print("---- 删除后,名单列表的数据----")
print(movieName)

3、改:即赋值,覆盖原先的元素即可

movieName=["加勒比海盗","黑客帝国","第一滴血","指环王","速度与激情"]
print("---- 改前,名单列表的数据----")
print(movieName)

##改
movieName[1]="骇客帝国"  ## 将“黑客帝国”改为“骇客帝国”
print("---- 改后,名单列表的数据----")
print(movieName)

4、查:指在或不在的意思。[ in , not in ]

namelist=["小张","小王","小李"]
findName=input("请输入你要查找的学生姓名:")
if findName in namelist:
    print(findName,"在名单列表中")
else:
    print(findName,"没找到")

5、排序及反转

  • index: 查找指定区间的指定元素,查找成功则返回元素的首个下标
my_list = ["a","b","c","a","b","c"]
print(my_list.index("a",1,4))  ## 可以指定范围精准查找某个元素,并返回该内容的第一个下标
print(my_list.index("a",1,3))  ## 找不到直接报错,范围区间左闭右开[1,3)
  • count:查找列表中指定元素的个数
print(my_list.count("b"))  ## 统计列表中某个元素的个数
  • reverse:逆序反转
str=[1,4,2,3]
print(str)      ## 原序输出
str.reverse()   ## 反转输出,也就是原序的逆序输出
print(str)
str.sort()      ## 将乱序数组进行升序排序输出
print(str)
str.sort(reverse=True) ## 将乱序数组升序排序后逆序输出,即降序
print(str)

6、菜品列表

list = [["宫保鸡丁",10],["鱼香肉丝",20],["回锅肉",30]]
print("请问您需要什么菜?")

menu = []
money = 0
for i in list:
    print(list.index(i),i[0],i[1])

while True:
    a = input()
    a = int(a)
    if a not in range(0,3):
        break
    print("您选择了:")
    menu.append(list[a])
    money = money + list[a][1]
    print(menu)
    print(money)

嵌套列表:类似于二位数组

实例:将8个老师,随机分配到3个办公室

import random
offices=[[],[],[]]
teachers=["a","b","c","d","e","f","g","h"]

## 将所有teachers全部随机追加到offices中
for name in teachers:
    index=random.randint(0,2)
    offices[index].append(name)
print(offices)

## 遍历嵌套列表offices,输出各办公室人数,及分别为哪些人

i=1
for office in offices:
    print("办公室%d的人数为:%d"%(i,len(office)))
    i+=1
    for name in office:
        print("%s"%name,end="\t")
    print("")
    print("-"*20)

实例 : 商品列表加入购物车

读入商品显示列表,并询问购买商品后加入购物车

## 另外可以使用枚举类型实现enumerate
# mylist=["a","b","c","d"]
# for i,con in enumerate(mylist):
#     print(i,con)

import time
products=[["huawei",8888],["iphone",6888,333],["MacPro",14800,"苹果"],["小米6",2499],["coffee",31],["Book",60],["Nike",699]]
print("-------商品列表-------")
j=0
nu = []
while j < len(products):
    print(j,end="\t")
    nu.append(j)
    i = 0
    while i < len(products[j]):
        print(products[j][i],end="\t")
        i+=1
    print("")
    j+=1

shoppingCart = []
while True:
    num=input("请输入您想购买的商品编号:[0|1|2|...]:")
    if num=="q":
        j = 0
        if len(shoppingCart)==0:
            exit("您没有购买任何商品")
        print("已退出,您的购物车清单如下--------")
        while j < len(shoppingCart):
            print(j, end="\t")
            i = 0
            while i < len(shoppingCart[j]):
                print(shoppingCart[j][i], end="\t")
                i += 1
            print("")
            j += 1
        time.sleep(3)
        exit()
    numInt=int(num)
    if numInt not in nu:
        print("输入错误,请输入商品编号:%d-%d"%(nu[0],nu[-1]))
        continue
    shoppingCart.append(products[numInt])
    buying=products[numInt]
    print("您购买的商品:%s 已加入购物车,请输入商品编号继续购买,退出请按q"%buying)

class 类

类就是一组数据的模板

  • 初始类
class cai():
    id = 0
    name = " "
    price = 0
    chushi = " "
    cost = 0

gong = cai()
gong.id = 1
gong.name = "gongbaojiding"
gong.price = 20
gong.chushi = "wangxiaohu"
gong.cost = 10

yu = cai()
yu.id = 2
yu.name = "yuxiangrousi"
yu.price = 40
yu.chushi = "zhangdachu"
yu.cost = 20

menu = [gong,yu]

for i in menu:
    print(i.id,i.name,i.price,i.chushi,i.cost)

order = []
money = 0
while True:
    a = input()
    a = int(a)
    print("您选择了:")
    for i in menu:
        if a == i.id:
            print(i.name) 
            order.append(i.name)
            money = money + i.price
    print(order)
    print(money)
  • 类的self
class dish():
    def __init__(self,mid,mname,mprice,mchushi,mcost):
        self.id = mid
        self.name = mname
        self.price = mprice
        self.chushi = mchushi
        self.cost = mcost 
    def pall(self,):
        print(self.id,self.name,self.price,self.chushi)
    def benefit(self,):
        print("benefit is %d"%(self.price - self.cost))

gong = dish(1,"gongbaojiding",15,"zhangfaha",5)
yu = dish(2,"yuxiangrosi",30,"wangxiaohu",19)

menu = [gong,yu]
for i in menu:
    i.pall()
    i.benefit()

order = []
money = 0
while True:
    a = input()
    a = int(a)
    print("您选择了:")
    for i in menu:
        if a == i.id:
            print(i.name) 
            order.append(i.name)
            money = money + i.price
    print("=================================")
    print(order)
    print(money)

posted on 2020-06-27 19:14  zhangfd  阅读(243)  评论(0编辑  收藏  举报