python之旅--数据类型

列表操作

 1 >>> info = [1,2,'a','b','python']
 2 >>> print(info)
 3 [1, 2, 'a', 'b', 'python']
 4 >>> print(info[0],info[2])
 5 1 a
 6 >>> print(info[1:3]) #切片
 7 [2, 'a']
 8 >>> print(info[3])
 9 b
10 >>> print(info[-1]) #取最后一个
11 python
12 >>> print(info[-2:]) #取最后两个值 从左到右 省略掉最后面的
13 ['b', 'python']
14 >>> print(info[:3]) #前面是零可以省略
15 [1, 2, 'a']
16 >>> #追加 插入
17 ... info.append("c")
18 >>> print(info)
19 [1, 2, 'a', 'b', 'python', 'c']
20 >>> info.insert(4,"d")
21 >>> print(info)
22 [1, 2, 'a', 'b', 'd', 'python', 'c']
23 >>> #删除
24 ... info.remove("a")
25 >>> print(info)
26 [1, 2, 'b', 'd', 'python', 'c']
27 >>> del info[1] #按下标删除
28 >>> print(info)
29 [1, 'b', 'd', 'python', 'c']
30 >>> info.pop() #删除最后一个
31 'c'
32 >>> print(info)
33 [1, 'b', 'd', 'python']
34 >>> #查询位置
35 ... print(info.index("python"))
36 3
37 >>> #统计
38 ... print(info.count("b"))
39 1
40 #扩展
41 >>> info2 = [3,"e"]
42 >>> info.extend(info2)
43 >>> print(info)
44 [1, 'b', 'd', 'python', 3, 'e']
45 #删除变量
46 >>> del info2

深浅copy
 1 >>> import copy #导入copy模块
 2 >>> list1 = ["a","b",["c","d"],"java"] #列表中可以嵌套列表
 3 >>> print(list1)
 4 ['a', 'b', ['c', 'd'], 'java']
 5 >>> list2 = list1.copy() #浅copy
 6 >>> print(list2)
 7 ['a', 'b', ['c', 'd'], 'java']
 8 >>> list3 = copy.deepcopy(list1) #深copy 需要导入copy模块
 9 >>> print(list3)
10 ['a', 'b', ['c', 'd'], 'java']
11 >>> list4 = list1 #赋值
12 >>> print(list4)
13 ['a', 'b', ['c', 'd'], 'java']
14 >>> list1[3] = "python" #修改列表父对象
15 >>> list1[2][0] = "v" #修改列表子对象
16 >>> print(list1) #打印修改后的列表
17 ['a', 'b', ['v', 'd'], 'python']
18 >>> print(list2) #只拷贝父对象,不会拷贝对象的内部的子对象 子对象会改变
19 ['a', 'b', ['v', 'd'], 'java']
20 >>> print(list3) #完全复制 拷贝对象及其子对象
21 ['a', 'b', ['c', 'd'], 'java']
22 >>> print(list4)
23 ['a', 'b', ['v', 'd'], 'python']
#联名账户 账户中余额都可以看到 账户名不改变
>>> person = ["name",["saving",100]]
>>> p1 = person[:]
>>> p2 = person[:]
>>> p1[0] = "A"
>>> p2[0] = "B"
>>> p1[1][1] = 50  #两个人都可以看到账号余额改变
>>> print(p1)
['A', ['saving', 50]] #各自的账号名 余额同步改变
>>> print(p2)
['B', ['saving', 50]]

 元组

存一组数据,一旦创建便不能修改,所以又叫只读列表

只有两个方法:index 和 count

>>> names = ('a','b','c','a')
>>> names.count('a')
2
>>> names.index('a')
0
>>> names.index('a',2)
3

程序练习

程序:购物车程序

需求:

  1.启动程序后,让用户输入工资,然后打印商品列表。

  2.允许用户根据商品编号购买商品。

  3.用户选择商品后,检测余额是否够,够直接扣钱,不够提醒。

  4.可随时退出,退出时,打印已购买商品和余额。

product_list = [
    ('iphone',5800),
    ('mac pro',12000),
    ('bike',800),
    ('watch',10600),
    ('coffee',33)
]
shopping_list = []
salary = input("input your salary:")
if salary.isdigit():  #判断是否整数
    salary = int(salary)
    while True:
        #for item in product_list:
            #print(product_list.index(item),item)

        for index,item in enumerate(product_list): #enumerate打出列表的下标
            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]
                if p_item[1] <= salary:
                    shopping_list.append(p_item)
                    salary -= p_item[1]
                    print("Added %s into shopping cart,your current balanec is \033[31;1m%s\033[0m" %(p_item,salary))
                else:
                    print("you balance is too small ")
        elif user_choice == 'q':
            print("---shopping list---")
            for p in shopping_list:
                print(p)
            print("your crrent balance:",salary)
            exit()
        else:
            print("invalid option")

字符串操作

>>> name = "my name is python"
>>> name.capitalize() #首字母大写
'My name is python'
>>> name.count("a") #计数
1
>>> name.center(50,"-") #50个字符,不够的用-补足
'----------------my name is python-----------------'
>>> name.endswith("on") #判断以什么结尾
True
>>> name.expandtabs(tabsize=30) #tab键长度
'my name is python'
>>> name.find("name") #查找 从哪个开头
3
>>> name[name.find("name")] #字符串切片
'n'
>>> name.index("a")
4
>>> print('ab123'.isalnum()) #是不是一个阿拉伯数字
True
>>> "my name is {name}".format(name="test") #格式化输出
'my name is test'
>>> "my name is {name}".format_map({'name':'test'}) #格式化输出
'my name is test'
>>> print('abC'.isalpha()) #纯英文字符
True
>>> print('1A'.isdecimal()) #是否十六进制
False
>>> print('123'.isdigit()) #是否一个整数
True
>>> print('name'.isidentifier()) #判断是不是一个合法的标识符
True
>>> print('a'.islower()) #是否小写
True
>>> print('22'.isnumeric()) #是不是一个数字
True
>>> print('My Name Is '.istitle()) #首字母大写
True
>>> print('My Name Is'.isprintable()) #是否可以打印 tty file drive file不能打印
True
>>> print('A'.isupper()) #是否大写
True
>>> print(''.join(['1','2','3'])) #列表转换为字符串
123
>>> print('+'.join(['1','2','3'])) #列表转换为字符串
1+2+3
>>> name.ljust(50,"*") #长度50 不够的右边补*
'my name is python*********************************'
>>> name.rjust(50,"*") #长度50 不够的左边补*
'*********************************my name is python'
>>> print('Abc'.lower()) #变成小写
abc
>>> print('Abc'.upper()) #变成大写
ABC
>>> print('  Abc \n  '.lstrip()) #去除左边的空格和回车
Abc

>>> print('  Abc \n  '.rstrip()) #去除右边的空格和回车
  Abc
>>> print('  Abc \n  '.strip()) #去除两边的空格和回车
Abc
>>> print("python".translate(str.maketrans("abpth",'12345'))) #一一对应替换
3y45on
>>> print("python python".replace("p","P",1)) #替换 最后一个参数为替换数量
Python python
>>> print("python python".rfind("y")) #找到最右边值的下标
8
>>> print("py th on".split()) #按照空格分成列表
['py', 'th', 'on']
>>> print("py th on".split("t")) #按照传参分成列表
['py ', 'h on']
>>> print('1+2\n+3+4'.splitlines()) #按换行分成列表
['1+2', '+3+4']
>>> print("python python".swapcase()) #全部转换为大写
PYTHON PYTHON
>>> print("python python".title()) #转换为标题
Python Python
>>> print("python".zfill(50)) #补位
00000000000000000000000000000000000000000000python

字典操作

字典是一种key - value的数据类型。

>>> #语法
... #字典是无序的 (没有下标)
... info = {
...     'stu01':'A',
...     'stu02':'B',
...     'stu03':'C'
... }
>>> #通过key取值 查询
... info['stu01']
'A'
>>> info['stu04'] #需要确定有这个值用这种方法,没有会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'stu04'
>>> info.get('stu04') #没有值时用get 不报错
>>> #修改
... info['stu01'] = 'D' #里面有数值直接修改
>>> info['stu04'] = 'E' #里面没有直接添加
>>> info
{'stu04': 'E', 'stu01': 'D', 'stu02': 'B', 'stu03': 'C'}
>>> #del 删除
... del info["stu04"]  #删除key为stu04的数据
>>> info
{'stu01': 'D', 'stu02': 'B', 'stu03': 'C'}
>>> info.pop("stu01") #删除stu01
'D'
>>> info
{'stu02': 'B', 'stu03': 'C'}
>>> info.popitem() #随机删除
('stu02', 'B')
>>> info
{'stu03': 'C'}
>>> del info #删除字典
>>> info
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'info' is not defined

>>> #字典操作
... info1 = {
...     'stu01':'A',
...     'stu02':'B',
...     'stu03':'C'
... }
>>>
>>> info2 = {
...     'stu01':'a',
...     'stu04':'D'
... }
>>>
>>> info1.update(info2) #合并修改
>>> info1
{'stu04': 'D', 'stu01': 'a', 'stu02': 'B', 'stu03': 'C'}
>>> info1.items() #把一个字典转换为列表
dict_items([('stu04', 'D'), ('stu01', 'a'), ('stu02', 'B'), ('stu03', 'C')])
>>> info3 = dict.fromkeys([1,2,3],"test") #初始化一个字典 三个key共享一个内存地址
>>> info3
{1: 'test', 2: 'test', 3: 'test'}
>>>
>>> #多级字典嵌套及操作
... menu = {
...     "北京":{
...         "海淀":'五道口',
...         "昌平":'沙河'
...     },
...     "上海":{
...         "闵行":'人民广场'
...     }
... }
>>> menu.setdefault("深圳",{"罗湖":"东门"}) #没有增加新的数据
{'罗湖': '东门'}
>>> menu
{'北京': {'海淀': '五道口', '昌平': '沙河'}, '上海': {'闵行': '人民广场'}, '深圳': {'罗湖': '东门'}}
>>>
>>> #字典的循环
... for i in info1:
...     print(i,info1[i])
...
stu04 D
stu01 a
stu02 B
stu03 C
>>> #把字典转换为列表 效率不高
... for k,v in info1.items():
...     print(k,v)
...
stu04 D
stu01 a
stu02 B
stu03 C

程序练习

程序: 三级菜单

需求: 

  1. 打印省、市、县三级菜单
  2. 可返回上一级
  3. 可随时退出程序

menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}

exit_flag = False #标志位

while not exit_flag:
    for i1 in menu:
        print(i1)
    choice1 = input("选择输入1>>")
    if choice1 in menu:
        while not exit_flag:
            for i2 in menu[choice1]:
                print("\t",i2)
            choice2 = input("选择输入2>>")
            if choice2 in menu[choice1]:
                while not exit_flag:
                    for i3 in menu[choice1][choice2]:
                        print("\t\t",i3)
                    choice3 = input("选择输入3>>")
                    if choice3 in menu[choice1][choice2]:
                        for i4 in menu[choice1][choice2][choice3]:
                            print("\t\t\t",i4)
                        choice4 = input("最后一层,按b返回>>")
                        if choice4 == "b":
                            pass
                        elif choice4 == "q":
                            exit_flag = True
                    if choice3 == "b":
                        break
                    elif choice3 == "q":
                        exit_flag = True
            if choice2 == "b":
                break
            elif choice2 == "q":
                exit_flag = True

猜你喜欢

转载自www.cnblogs.com/wangzihong/p/9043328.html