基本数据类型

一、基本数据类型

列表

 1 #! /usr/bin/enc python
 2 # -*- coding:utf-8 -*-
 3 
 4 # 列表
 5 name_list = ['alex', 'wenzm', 'eric']
 6 
 7 # 索引
 8 print(name_list[0])    # 打印索引为0的元素
 9 print(name_list[2:len(name_list)])    # 打印索引>=2 小于序列长度的元素
10 
11 # 列表提供的房法
12 # append():在列表元素末尾追加
13 name_list.append('James')
14 # count():返回某一元素在列表中出现的次数
15 name_list.count('alex')
16 # extend():扩展,逐一追加
17 temp = ['first', 'second']
18 name_list.extend(temp)
19 # index():索引
20 name_list.index('alex')    # 返回元素的索引值
21 # insert():插入
22 name_list.insert(1, 'sb')    # 在索引为1的位置插入元素
23 # pop():移除掉末尾元素并返回
24 a = name_list.pop()    #移除掉末尾元素并赋值给了a变量
25 # remove():移除某元素,如果有多个只移除从左到右找到的第一个
26 name_list.remove('wenzm')    # 移除指定元素
27 # reverse():倒叙(翻转)
28 name_list.reverse()
29 # sort():排序
30 name_list.sort()

元组

 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 # 元组
 5 name_tuple = ('alex', 'eric')
 6 # 索引
 7 print(name_tuple[0])    #打印第0个索引位置的元素
 8 # len():长度
 9 print(len(name_tuple))    # 打印元组的长度
10 # 切片
11 print(name_tuple[0:1])    # 打印第0到第一个元素
12 # 循环取
13 for i in name_tuple:
14     print(i)
15 # 元组不能删除
16 # count():返回元素出现的个数
17 print(name_tuple.count('alex'))
18 # index():返回元素的索引位置
19 print(name_tuple.index('alex'))

字典

 1 #! /usr/bin/env python 
 2 # -*- coding:utf-8 -*-
 3 
 4 user_info = {
 5     'name':'alex',
 6     'age':33,
 7     'gender':'M'
 8 }
 9 
10 # 字典内置的功能
11 # 索引
12 print(user_info['name'])    #获取字典指定的key对应的value
13 # 切片:字典没有办法切片,因为key不是连续的
14 # 循环
15 for key in user_info:
16     print(key)      # 默认输出了所有的键
17 
18 for value in user_info.values():
19     print(value)    # 循环打印所有的值
20 print(user_info.keys())    #打印所有的键key
21 print(user_info.values())   #打印所有的值value
22 print(user_info.items())    # 打印所有的键值对
23 
24 for key, value in user_info.items():
25     print(key, value)       # 打印所有的键值对
26 
27 # clear(): 清除所有内容
28 #print(user_info.clear())
29 
30 # get():根据key获取值,存在则返回对应value,如果key不存在,返回none
31 print(user_info.get('name'))
32 print(user_info['name'])    # 通过索引key取,如果不存在会报错,推荐使用get()
33 
34 # has_key():检查字典中指定的key知否存在 python3以后没有此方法
35 #print(user_info.has_key('name'))
36 print('name' in user_info.keys())
37 
38 # pop():移除指定key的键值对并将他返回
39 # a = user_info.pop('name')
40 # print(a)
41 # print(user_info)
42 
43 # popitem():移除字典末尾的键值对并返回
44 print(user_info)
45 a = user_info.popitem()
46 print(a)
47 print(user_info)
48 
49 # update():批量更新,可以吧新的字典在后面追加到云字典中
50 print(user_info)
51 test = {
52     'a':123,
53     'b':456,
54 }
55 user_info.update(test)
56 print(user_info)
57 
58 # 删除指定索引的键值对
59 del test['a']
60 print(test)

其他

enumerate()自动生成一列,从0开始自增1

 1 #! /usr/bin/env python 
 2 # -*- coding:utf-8 -*-
 3 
 4 enumerate() 给列表自动生成一列,默认从0开始,自增1,如果有指定参数,则从给的参数开始
 5 sop_li = ['电脑','鼠标','显示器','电源','飞机']
 6 for index, item in enumerate(sop_li, 1):
 7     print(index, item)
 8 inp = int(input('请输入商品:'))  # int()转换成数字
 9 print(sop_li[inp-1])
10 
11 #range,xrange
12 #range:用来获取指定范围内的数。range(0,10000)
13 #py2.7
14 # for i in xrange(1, 1000):
15 #     print(i)
16 # py3+
17 for i in range(1, 10):
18     print(i)
19 
20 for i in range(10, 1, -1):
21     print(i)
22 li = ['alex', 'eric']
23 print(li)
24 for i in range(len(li)):
25     print(i, li[i])

 练习题:

一、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 a = {
 5     'k1':[],    # 创建列表用于存储多个数
 6     'k2':[],
 7 }
 8 
 9 li1 = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
10 for i in li1:
11     if i > 66:
12         a['k1'].append(i)
13     else:
14         a['k2'].append(i)
15 
16 print(a)

 

二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
 
 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 li = ["alec", " aric", "Alex", "Tony", "rain"]
 5 tu = ("alec", " aric", "Alex", "Tony", "rain")
 6 dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
 7 for i in li:
 8     print(i.strip())
 9     # 先转换为大写
10     if i.capitalize().startswith('a') and i.endswith('c'):
11         print(i)
12 
13 for i in tu:
14     # print(i.strip())
15     if i.startswith('a') or i.startswith('A') and i.endswith('c'):
16         print(i)
17 for k, v in dic.items():
18     print(v.strip())
19     if v.startswith('a') or v.startswith('A') and v.endswith('c'):
20         print(v)

 

 
三、输出商品列表,用户输入序号,显示用户选中的商品
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']
 
 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 li = ["手机", "电脑", '鼠标垫', '游艇']
 5 
 6 li2 = ["手机", "电脑", '鼠标垫', '游艇']
 7 for index, item in enumerate(li2, 1):
 8     print(index, item)
 9 inp = int(input("请选择商品:"))
10 print(li2[inp-1])

 

四、购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物车
  •  1 #! /usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 
     4 shopp = []
     5 money = int(input("请输入资产:"))
     6 cost = 0
     7 active = True
     8 while active:
     9     for index, item in enumerate(goods, 1):
    10         print(index, item)
    11     inp = input("请选择商品q退出:")
    12     if inp == 'q':
    13         active = False
    14     else:
    15         inp = int(inp)
    16         if money > int(goods[inp-1]['price']):
    17             shopp.append(goods[inp-1])
    18             money -= goods[inp-1]['price']
    19             cost += goods[inp-1]['price']
    20             print("购买了{}".format(goods[inp - 1]))
    21         else:
    22             print("只剩${}!".format(money))
    23             active = False
    24 
    25 print("共花费${}".format(cost))
    26 print("已买到商品如下:".center(20, '-'))
    27 for index, item in enumerate(shopp, 1):
    28     print(index, item['name'])
    29 print("还剩${}".format(money))

    五、用户交互,显示省市县三级联动的选择

     1 dic = {
     2     "河北": {
     3         "石家庄": ["鹿泉", "藁城", "元氏"],
     4         "邯郸": ["永年", "涉县", "磁县"],
     5     }
     6     "河南": {
     7         ...
     8     }
     9     "山西": {
    10         ...
    11     }
    12  
    13 }
    14 
    15 while True:
    16     for key in dic:
    17         print(key)
    18     inp = input("请输入省任意键返回上一层:")
    19     if inp in dic:
    20         while True:
    21             for i in dic[inp]:
    22                 print('\t',i)
    23             inp1 = input("请输入市任意键返回上一层:")
    24             if inp1 in dic[inp]:
    25                 while True:
    26                     for i in dic[inp][inp1]:
    27                         print('\t\t', i)
    28                     inp2 = input("最后一层,按q返回上一层:")
    29                     if inp2 == 'q':
    30                         break
    31             else:
    32                 break
    33     else:
    34         break

 

六、str和bytes

 

str和bytes之间的转换

 1 #! /use/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 name = '李璐'
 5 for i in name:
 6     print(i)
 7 # python3+循环的时候是循环每一个字符
 8 # 字符 —> 字节 byte_list = bytes('字符串', encoding = 'utf-8') 返回的是字节,默认每个字节都是16进制表示
 9 # 循环 改字节是用10进制进行循环
10 # bytes('字符串')
11 # utf-8 一个字符是三个字节,一个字节是8位
12 # gbk 一个字符是两个字节
13 
14 
15 # 转换成bytes
16 name_by = bytes(name, encoding = 'utf-8')    # 编码格式为utf-8
17 print(name_by)
18 name_by1 = bytes(name, encoding = 'gbk')
19 
20 # 转换成str
21 # 同样的bytes类型转换成str,注意转换的时候编码格式一定要准确
22 new_name = str(name_by, encoding = 'utf-8')
23 print(new_name)
24 new_name1 = str(name_by, encoding = 'gbk')    # 此时会报编码格式不正确,因为name_by是用utf-8转换的
25 print(new_name1)
26 new_name2 = str(name_by1, encoding = 'gbk')
27 print(new_name2)
28 
29 """
30 什么时候用str()什么时候用bytes?
31 s = str()   要么是创建字符串,要么是转换成字符串,字节转换成字符串时要知道字节编码格式
32 b = bytes() 同样要么创建字节,要么是转换成字节,转换的时候同样要知道字符串的编码格式
33 """

列表,列表嵌套

 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 # 列表
 5 # list
 6 #     list()
 7 #     list 类__init__
 8 
 9 """
10 str() ->创建字符串,或将其他的转换成字符串
11 -------------------------------------
12 str() ->创建列表,或将其他的转换成列表
13 1、创建
14 li = [12,34,5,21,123]
15 li1 = list()
16 li1 = list([12,34,5,21,123])
17 2、转换
18 for 循环,字符可迭代
19 s = '李璐'
20 li = list(s)    # for循环,将循环每一个元素,当做列表的元素在列表中生成 ['李','璐']
21 t = ('james', 'haeden', 'alex')
22 new_t = list(t)
23 dic = {'k1':'alex','k2':'james'}
24 li3 = list(dic)
25 li4 = list(dic.)
26 print(li3)
27 """
28 dic = {'k1':'alex','k2':'james'}
29 li3 = list(dic)
30 li4 = list(dic.items())
31 print(li3)
32 print(li4)
33 # li3.append()  追加
34 # li3.clear() 清除
35 # li3.extend()    扩展本身,用另外一个可迭代的对象扩充到末尾
36 s = '李璐'
37 li = [11,33,22]
38 li.extend(s)    # 将s中的每个元素扩充到li末尾
39 print(li)
40 # li3.reverse()  反转,内部元素反转
41 # li3.insert()  向指定索引位置插入元素
42 li.insert(1,'X')
43 print(li)

44 # c.公共功能 45 li = ['alex', 'eric', 'james', '123'] 46 # 索引 47 print(li[2]) 48 print(type(li[2])) # 取得类型为字符串 49 # 切片 50 print(li[2:3]) 51 print(type(li[2:3])) # 原本是什么类型,就是什么类型 52 # for 53 # len()


54 # 列表嵌套 55 l = ['alex', 'eroc', { 56 'k1':'v1', 57 'k2':{ 58 'kk1':'123', 59 'kk2':(11,22,33) 60 } 61 }] 62 #列表嵌套找到11 63 print(l[2]) #{'k1': 'v1', 'k2': {'kk1': '123', 'k2': (11, 22, 33)}} 64 print(l[2]['k2']) #{'kk1': '123', 'k2': (11, 22, 33)} 65 print(l[2]['k2']['kk2']) #(11, 22, 33) 66 print(l[2]['k2']['kk2'][0]) #11

元组、字典嵌套

 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 # 元组
 5 #   a.创建和转换
 6 #   t = (11,22,33)
 7 #   t = tuple((11,22,33))
 8 #   t = tuple([])   字符串、列表、字典
 9 #   b.特有方法
10 #    count() index()
11 #   c.嵌套(元素不可修改)
12 #   d.元组的特性,不可修改,谁不可修改元组的元素不可被修改,但是元素里面的元素可以被修改
13 t = ('alex', 'eric', ['james', {'k1':'v1'}])
14 print(t)
15 t[2].append('wzm')
16 print(t)
17 t[2][1]['k2'] = 123
18 print(t)
19 t[2][1].update({'k3':'234'})
20 print(t)
21 
22 #   一般的,字符串执行一个功能,会生成一个新的对象,并在内存中保存,自身不变
23 #          列表、元组、字典执行一个功能,自身会发生变化
24 
25 #字典
26 #   1.创建
27 a = {'k1':'v1', 'k2':'v2'}
28 a1 = dict(k1 = 123, k2 = 234)
29 print(a)
30 print(a)
31 #   2.列表转换字典
32 li = [11,22,33]
33 new_dic = dict(enumerate(li, 1))   # enumerate()自动新增了索引列,并自增1
34 print(new_dic)
35 #   3.字典内部功能
36 # keys()
37 # valus()
38 # items()
39 # pop()
40 # popitem()
41 # get()
42 # fromkeys()
43 n = new_dic.fromkeys([1,2], 'wzm')  # 创建了两个字典的key为1,2值都是wzm
44 print(n)
45 n1 = dict.fromkeys(['k1', 'k2', 'k3'],[])   # 此时创建的是同一个列表
46 print(n1)
47 n1['k1'].append('x')    # append(),k1,k2,k3都会添加
48 print(n1)

 

set
1、创建
s = set()
s = {11,22,33,44}
2、转换
l = '123'
l = (1,2,3)
l = [1,2,3]
s = set(l)
s = set([1,2,3])
s = set((1,2,3))

3、set提供的方法
add()

clear()

difference()
l = [1,2,3,4,1,1,5]
l2 = (1,2,3,8,7)
s = set(l)
s1 = set(l2)
s3 = set()
s4 = set()
s3 = s.difference(s1) # 找s中存在s1中不存在的集合并返回
s4 = s1.difference(s) # 找s1中存在s中不存在的集合并返回

difference_update()
s.difference_update(s1) # 找s中存在s1中不存在的集合并更新自己

 

 1 #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 
 5 # 数据库中原有
 6 old_dict = {
 7     "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
 8     "#2": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
 9     "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
10 }
11 
12 # cmdb 新汇报的数据
13 new_dict = {
14     "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 800},
15     "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
16     "#4": {'hostname': 'c2', 'cpu_count': 2, 'mem_capicity': 80},
17 }
18 需要删除:?
  需要新建:?
  需要更新:? 
  注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
19 old_keys = old_dict.keys() 20 new_keys = new_dict.keys() 21 # print(old_keys) 22 # print(new_keys) 23 old_set = set(old_keys) 24 new_set = set(new_keys) 25 # print(old_set) 26 # print(new_set) 27 update_set = old_set.intersection(new_set) 28 del_set = old_set.difference(new_set) 29 # print(update_set) 30 # print(del_set) 31 # for key in update_set: 32 # old_dict. 33 # print(old_dict) 34 update_dict = {} 35 for key in update_set: 36 update_dict= new_dict[key] 37 38 print(update_dict) 39 print(old_dict) 40 41 old_dict.update(update_dict) 42 print(old_dict)

 

posted @ 2020-05-03 14:35  H年轻的心  阅读(34)  评论(0)    收藏  举报