码迷,mamicode.com
首页 > 编程语言 > 详细

python-python基础2

时间:2020-02-15 09:52:22      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:padding   vertica   ace   通过   南京   cal   dex   only   mono   

一、列表、元组操作

列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

names=["zhangzhihao","jehu","xiaodu","jjj","aaa"]
print(names[1])
#从第2个取到第4个,但不包括第4个
print(names[1:3])  #切片,顾头不顾尾
print(names[0:3])
#取倒数第二个值
print(names[-2])
#取最后两个值
print(names[-2:])

执行结果:

jehu
[‘jehu‘, ‘xiaodu‘]
[‘zhangzhihao‘, ‘jehu‘, ‘xiaodu‘]
jjj
[‘jjj‘, ‘aaa‘]

追加

names=["zhangzhihao","jehu","xiaodu","jjj","aaa"]
names.append("www")
print(names)

执行结果:

[‘zhangzhihao‘, ‘jehu‘, ‘xiaodu‘, ‘jjj‘, ‘aaa‘, ‘www‘]

插入

names=["zhangzhihao","jehu","xiaodu","jjj","aaa"]
names.insert(1,"rrr")
print(names)

执行结果:

[‘zhangzhihao‘, ‘rrr‘, ‘jehu‘, ‘xiaodu‘, ‘jjj‘, ‘aaa‘]

修改

names=["zhangzhihao","jehu","xiaodu","jjj","aaa"]
names[0]="zhangzz"
print(names)

执行结果:

[‘zhangzz‘, ‘jehu‘, ‘xiaodu‘, ‘jjj‘, ‘aaa‘]

删除

方法一:

names=["zhangzhihao","jehu","xiaodu","jjj","aaa"]
names.remove("aaa")
print(names)

执行结果:

[‘zhangzhihao‘, ‘jehu‘, ‘xiaodu‘, ‘jjj‘]

方法二:

names=["zhangzhihao","jehu","xiaodu","jjj","aaa"]
del names[3]
print(names)

执行结果:

[‘zhangzhihao‘, ‘jehu‘, ‘xiaodu‘, ‘aaa‘]

方法三:

#删掉jjj
names=["zhangzhihao","jehu","xiaodu","jjj","aaa"]
names.pop(3)
print(names)

查找某个字符串在列表中的哪个位置

names=["zhangzhihao","jehu","xiaodu","jjj","aaa"]
print(names.index("xiaodu"))

统计列表中字符串的数量

names=["zhangzhihao","jehu","xiaodu","jjj","aaa","jjj"]
print(names.count("jjj"))

清空列表

names=["zhangzhihao","jehu","xiaodu","jjj","aaa","jjj"]
names.clear()
print(names)

翻转列表

names=["zhangzhihao","jehu","xiaodu","jjj","aaa","jjj"]
names.reverse()
print(names)

执行结果:

[‘jjj‘, ‘aaa‘, ‘jjj‘, ‘xiaodu‘, ‘jehu‘, ‘zhangzhihao‘]

排序

names=["zhangzhihao","jehu","xiaodu","jjj","aaa","jjj"]
names.sort()
print(names)

执行结果:

[‘aaa‘, ‘jehu‘, ‘jjj‘, ‘jjj‘, ‘xiaodu‘, ‘zhangzhihao‘]

合并列表

names=["zhangzhihao","jehu","xiaodu","jjj","aaa","jjj"]
names2=["1","2","3","4","5"]
print(names)
names.extend(names2)
print(names)

执行结果:

[‘zhangzhihao‘, ‘jehu‘, ‘xiaodu‘, ‘jjj‘, ‘aaa‘, ‘jjj‘]
[‘zhangzhihao‘, ‘jehu‘, ‘xiaodu‘, ‘jjj‘, ‘aaa‘, ‘jjj‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]

复制

copy 浅复制

names=["zhangzhihao","jehu","xiaodu","jjj","aaa","jjj"]
names2=names.copy()
print(names)
print(names2)
number=["1","2","3",["a","b","c"],"4","5"]
number2=number.copy()
number[2]="666"
print(number)
print(number2)
number[3][0]="A"
print(number)
print(number2)

执行结果:

[‘1‘, ‘2‘, ‘666‘, [‘a‘, ‘b‘, ‘c‘], ‘4‘, ‘5‘]
[‘1‘, ‘2‘, ‘3‘, [‘a‘, ‘b‘, ‘c‘], ‘4‘, ‘5‘]
[‘1‘, ‘2‘, ‘666‘, [‘A‘, ‘b‘, ‘c‘], ‘4‘, ‘5‘]
[‘1‘, ‘2‘, ‘3‘, [‘A‘, ‘b‘, ‘c‘], ‘4‘, ‘5‘]

把number复制到number2,修改number中的元素本不应该影响number2,但是如果number中还有一层列表,修改number会影响number2

深复制

import copy

number=["1","2","3",["a","b","c"],"4","5"]
number2=copy.deepcopy(number)
number[2]="666"
number[3][0]="A"
print(number)
print(number2)

 

元组

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法:names = ("alex","jack","eric")

它只有2个方法,一个是count,一个是index,完毕。

 

练习:

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额
salary=input("Please input your salary:")
commodities=[["Iphone",5800],["Milk",30],["apple",15],["coffee",20],["chicken",25],
             ["pork",32],["juice",8],["router",700]]
brougth_com=[]

if salary.isdigit():
    salary=int(salary)
    while True:
        for index,i in enumerate(commodities):
            print(index,i)
        com_chose = input("The item number you want to buy:")
        if com_chose.isdigit():
            com_chose=int(com_chose)
            if com_chose<len(commodities) and com_chose>=0:
                price=commodities[com_chose][1]
                if salary>=price:
                    salary=salary-price
                    brougth_com.append(commodities[com_chose])
                    print("Have added {0} to the shopping cart and your current balance is \033[31;1m{1}\033[0m".format(commodities[com_chose][0],salary))
                else:
                    print("Your balance is short, only {0} left.".format(salary))
            else:
                print("Over the goods number range.")
        elif com_chose=="q":
            print("------shopping list-------")
            for j in brougth_com:
                print(j)
            print("Your balance is {0}.".format(salary))
            exit()
        else:
            print("invalid option.")
else:
    print("invalid option.")

 

二、字典

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

字典的特性:

  • dict是无序的
  • key必须是唯一的,so 天生去重

语法:

info = {
    1: "zhangzhihao",
    2: "liuxiaodu",
    3: "jehu",
}

增加

info["4"]="aaa"
print(info)

执行结果:

{‘1‘: ‘zhangzhihao‘, ‘2‘: ‘liuxiaodu‘, ‘3‘: ‘jehu‘, ‘4‘: ‘aaa‘}

修改

info["1"]="zhangzz"
print(info)

执行结果:

{‘1‘: ‘zhangzz‘, ‘2‘: ‘liuxiaodu‘, ‘3‘: ‘jehu‘}

删除

方法一:

info.pop("2")
print(info)

执行结果:

{‘1‘: ‘zhangzhihao‘, ‘3‘: ‘jehu‘}

方法二:

del info["2"]
print(info)

执行结果:

{‘1‘: ‘zhangzhihao‘, ‘3‘: ‘jehu‘}

查找

b=info.get("2")
print(b)
a=info["2"]
print(a)

执行结果:

liuxiaodu

liuxiaodu

如果一个key不存在,就报错,get不会,不存在只返回None

多级字典嵌套及操作

city={
    "广东":{
        "广州":["越秀","天河","荔湾","白云"],
        "深圳":["南山","罗湖","福田","宝安"],
        "茂名":["茂南","茂港","电白","高州"]},
    "浙江":{
        "杭州":["西湖","萧山","余杭"],
        "温州":["鹿城","龙湾","瓯海"],
        "嘉兴":["南湖","秀洲","平湖"]},
    "上海":{
        "黄埔":["南京路","外滩","豫园"],
        "徐汇":["湖南路","天平路","枫林路"],
        "长宁":["华阳路","新华路","江苏路"]
    }
}
print(city)
print(city["广东"])
print(city["广东"]["深圳"])

执行结果:

{‘广东‘: {‘广州‘: [‘越秀‘, ‘天河‘, ‘荔湾‘, ‘白云‘], ‘深圳‘: [‘南山‘, ‘罗湖‘, ‘福田‘, ‘宝安‘], ‘茂名‘: [‘茂南‘, ‘茂港‘, ‘电白‘, ‘高州‘]}, ‘浙江‘: {‘杭州‘: [‘西湖‘, ‘萧山‘, ‘余杭‘], ‘温州‘: [‘鹿城‘, ‘龙湾‘, ‘瓯海‘], ‘嘉兴‘: [‘南湖‘, ‘秀洲‘, ‘平湖‘]}, ‘上海‘: {‘黄埔‘: [‘南京路‘, ‘外滩‘, ‘豫园‘], ‘徐汇‘: [‘湖南路‘, ‘天平路‘, ‘枫林路‘], ‘长宁‘: [‘华阳路‘, ‘新华路‘, ‘江苏路‘]}}
{‘广州‘: [‘越秀‘, ‘天河‘, ‘荔湾‘, ‘白云‘], ‘深圳‘: [‘南山‘, ‘罗湖‘, ‘福田‘, ‘宝安‘], ‘茂名‘: [‘茂南‘, ‘茂港‘, ‘电白‘, ‘高州‘]}
[‘南山‘, ‘罗湖‘, ‘福田‘, ‘宝安‘]

 循环查字典

#方法1
for key in info:
    print(key,info[key])

#方法2
for k,v in info.items(): #会先把dict转成list,数据里大时莫用
    print(k,v)

 

 

 

python-python基础2

标签:padding   vertica   ace   通过   南京   cal   dex   only   mono   

原文地址:https://www.cnblogs.com/jehuzzh/p/12310520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!