- int:整数。 1,2,3 加减乘除等运算。
- str:字符串。‘1,2,3’ ,‘hello’ 存储少量的数据,进行简单的操作。
- list:列表。 ['hello',1,'1',['world']] 存储大量的数据。
- tuple:元祖。只读列表。
- dict:{'name':'root'} 查询速度快,存储的是关系型数据。
- set{}
int
不可变类型。进行数字运算操作。
字符串转int: int('字符串')
ascii码与字符串转换:
>>> chr(100) 'd' >>> ord('d') 100
str
引号里面的全是字符串。单引号、双引号、多引号。多引号用于包含多行。
字符串为不可变类型。
字符串可以加(字符串与字符串)、乘(字符串与整数)。
str方法:
str.capitalize() 首字母大写,其余小写。
str.swapcase() 大小写翻转。
str.title() 非字母隔开的每个单词首字母大写。
str.center(30,'*')设置总长度为30.字符串居中,用‘*’填充。
str.upper()全部大写
str.lower()全部小写
str.startswith('ab') 字符串是否以‘ab’开始。注意‘ab’为一个整体。
str.endswith('ab') 字符串是否以‘ab’结束。
str.strip() 默认去除字符串首尾的空格、换行符、制表符等。可定制去除内容。需要注意的是,自定去除的内容会当成单字符串来去除。
>>> ss = 'abclaonanhaiq' >>> ss.strip('aqbc') 'laonanhai'
str.replace() 替换。可制定替换多少次。
str.split() 分割。str-->list
str.join() list-->str
str.find() 找元素的索引,找不到返回’-1‘.
str.index() 找不到报错。
str.format() 格式化输出。
公共方法:
len() 计算元素个数。
count()计算某个特定元素个数。
str类型转换
str --> int 字符还全部由数字组成 int('123')
int --> str str(1)
int --> bool bool(0) 0:False 非0:True
bool --> int int(True):1 int(False):0
str --> bool 非空True 空字符串False
bool --> str str(True) str(bool)
str -->list str.split()
list -->str str.join(list)
str切片
str[起始:结束:步长] 顾头不顾尾。
str格式化输出
% 占位符。 s:字符串 d:数字
运算符:
优先级:() > not > and > or
x or y if x is True,return x
list
可变数据类型。
list切片:与字符串一致。取出来的是列表(一个元素的列表)。
增:
lst.append() 追加
lst.inset(索引,元素) 插入
lst.extend()迭代元素,分别插入。
删:
lst.pop()按照索引位置删除,唯一有返回值。
lst.remove()按照元素删。
lst.clear() 清空列表。
del lst 删除列表
del lst[索引] 按照索引删除
del lst[start:stop] 按切片删除
改:
lst[0] = 'NEW' 按照索引改。
lst[start:stop] = ‘new’ 按照切片改。
查:
按照索引,切片查。
for 循环遍历。
其他方法:
len(lst) 总元素个数。
lst.count('root') 'root'元素个数。
lst.sort() 排序
lst.reverse() 反转
tuple
只读列表,不可变数据类型。
dict
3.5版本包括3.5之前都是无序的。
增:
dic[key] = value 没有的话增加,有的话修改。
dic.setdefault(key, value)有key不修改,无key添加。
删:
dic.pop(key) 删除项。 有返回值。
dic.popitem() 3.5及3.5前随机删除。有返回值。3.5后删除最后一项。
dic.clear()清空。
del
del dic 删除字典。
del dic[key] 删除某一项。
改:
dic[key] = value 无加。有改。
dic1.update(dic2) 用dic2去更新dic1
查:
dic[key] key不存在就报错。
dic.get(key,自定义内容)。
dic.keys() dic.values() dic.items()
fromkeys
>>> d = dict.fromkeys('abc',666) >>> d['a'] = 888 >>> d {'a': 888, 'b': 666, 'c': 666} >>> d = dict.fromkeys('abc',[]) >>> d {'a': [], 'b': [], 'c': []} >>> d['a'].append(666) >>> d {'a': [666], 'b': [666], 'c': [666]}
一些题:

1 #-*- coding:utf-8 -*- 2 #version: 3.6.4 3 4 dic = {'name_list':['高猛', '于其',], 5 1:{ 6 'alex': '李杰', 7 'high': '175', 8 } 9 } 10 # ['高猛', '于其',] 追加一个元素'wusir', 11 12 dic['name_list'].append('wusir') 13 print(dic) 14 #{'alex': '李杰','high': '175' } 增加一个键值对 'sex': man, 15 dic[1]['sex'] = 'man' 16 print(dic)

1 l1 = [11, 22, 33, 44, 55] 2 # 将索引为奇数对应的元素删除。 3 for i in range(len(l1)-1,-1,-1): 4 if i % 2 == 1: 5 l1.pop(i) 6 print(l1)
PS:在循环一个列表时,不要改变列表的大小,这样会影响结果

1 dic = {'k1': 'v1', 'k2': 'v2', 'k3':'v3', 'name':'alex'} 2 # 删除key中带‘k’的键值对 3 lst = [] 4 for key in dic.keys(): 5 if 'k' in key: 6 lst.append(key) 7 for key in lst: 8 dic.pop(key) 9 print(dic)
ps:dictionary changed size during iteration.
购物车:
写一个购物车,写完了的写三级菜单。 购物车 功能要求: 要求用户输入总资产,例如:2000 显示商品列表,让用户根据序号选择商品,加入购物车 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。 goods = [{"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ]

1 goods = [{"name": "电脑", "price": 1999}, 2 {"name": "鼠标", "price": 10}, 3 {"name": "游艇", "price": 20}, 4 {"name": "美女", "price": 998}, 5 ] 6 shopping = {} 7 while True: 8 assets = input("Please enter your fixed assets: ") 9 if not assets.isdigit() or int(assets) <= 0: 10 print("Input illegal") 11 continue 12 else: 13 assets = int(assets) 14 break 15 for index, key in enumerate(goods, 1): 16 print("Number:{}\tGoods is {}. Price is {}".format(index, key["name"], key["price"])) 17 while True: 18 choose = input("Please enter the product number you want to purchase. Exit by Q:") 19 if choose.lower() == "q": 20 if shopping: 21 for good, count in shopping.items(): 22 print("You bought {} {}.".format(good, count)) 23 print("Your current balance is {}. Looking forward to your next visit.".format(assets)) 24 break 25 if not choose.isdigit() or int(choose) > len(goods) or int(choose) < 1: 26 print("Input illegal") 27 continue 28 else: 29 choose = int(choose) 30 if assets > goods[choose - 1]["price"]: 31 if goods[choose - 1]["name"] not in shopping: 32 shopping[goods[choose - 1]["name"]] = 0 33 shopping[goods[choose - 1]["name"]] += 1 34 assets -= goods[choose - 1]["price"] 35 print("Buy {} success. Your current balance is {}".format(goods[choose - 1]["name"], assets)) 36 continue 37 else: 38 flag = False 39 while True: 40 charge = input("The balance is insufficient. Please charge it. Exit by Q:").strip() 41 if charge.lower() == "q": 42 if shopping: 43 for good, count in shopping.items(): 44 print("You bought {} {}.".format(good, count)) 45 print("Your current balance is {}. Looking forward to your next visit.".format(assets)) 46 flag = True 47 break 48 49 if charge.isdigit() and int(charge) > 0: 50 assets += int(charge) 51 print("Top-up success. Your current balance is {}".format(assets)) 52 break 53 else: 54 print("Input illegal. Program exits") 55 continue 56 if flag: 57 break