python数据类型详解及列表字典集合推导式详解
一.运算符
Python语言支持以下类型的运算符:
- 算术运算符
如:
#!/usr/bin/env python # -*- coding:utf-8 -*- a = 5 b = 6 print(a + b)
- 比较运算符
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- a = 5 b = 6 if a < b: print(True) else: print(False)
- 赋值运算符
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- a = 5 b = a print(b)
- 逻辑运算符
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- a = 5 b = 6 if a >4 and b < 10: print(True) else: print(False)
- 成员运算符
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- value = "a" list = ['a','b'] if value in list: print(True)
二.数据类型
- 数字
int(整形),数字数据类型用于存储数值
Python 支持三种不同的数值类型:
- 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用,所以 Python3 没有 Python2 的 Long 类型。
- 浮点型(float) - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)
- 复数- 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型
class int(object): """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) """ def bit_length(self): """ 返回表示该数字的时占用的最少位数 """ """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ 返回该复数的共轭复数 """ """ Returns self, the complex conjugate of any int. """ pass def __abs__(self): """ 返回绝对值 """ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): """ x.__add__(y) <==> x+y """ pass def __and__(self, y): """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): """ 比较两个数大小 """ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): """ 强制生成一个元组 """ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): """ 相除,得到商和余数组成的元组 """ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): """ x.__div__(y) <==> x/y """ pass def __float__(self): """ 转换为浮点类型 """ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, name): """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown """ 内部调用 __new__方法或创建对象时传入参数使用 """ pass def __hash__(self): """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" """ x.__hash__() <==> hash(x) """ pass def __hex__(self): """ 返回当前数的 十六进制 表示 """ """ x.__hex__() <==> hex(x) """ pass def __index__(self): """ 用于切片,数字无意义 """ """ x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x, base=10): # known special case of int.__init__ """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) # (copied from class doc) """ pass def __int__(self): """ 转换为整数 """ """ x.__int__() <==> int(x) """ pass def __invert__(self): """ x.__invert__() <==> ~x """ pass def __long__(self): """ 转换为长整数 """ """ x.__long__() <==> long(x) """ pass def __lshift__(self, y): """ x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): """ x.__mul__(y) <==> x*y """ pass def __neg__(self): """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): """ x.__nonzero__() <==> x != 0 """ pass def __oct__(self): """ 返回改值的 八进制 表示 """ """ x.__oct__() <==> oct(x) """ pass def __or__(self, y): """ x.__or__(y) <==> x|y """ pass def __pos__(self): """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): """ 幂,次方 """ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): """ x.__radd__(y) <==> y+x """ pass def __rand__(self, y): """ x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): """转化为解释器可读取的形式 """ """ x.__repr__() <==> repr(x) """ pass def __str__(self): """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" """ x.__str__() <==> str(x) """ pass def __rfloordiv__(self, y): """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): """ x.__rxor__(y) <==> y^x """ pass def __sub__(self, y): """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): """ 返回数值被截取为整形的值,在整形中无意义 """ pass def __xor__(self, y): """ x.__xor__(y) <==> x^y """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 分母 = 1 """ """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 虚数,无意义 """ """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 分子 = 数字大小 """ """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 实属,无意义 """ """the real part of a complex number""" int
2.布尔值
真或者假,1或者0
3.字符串
字符串是python中最常见类型,我们通常用单引号('')或者双引号("")来创建
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- value = "a" print(value)
- 移除空白
例;
#!/usr/bin/env python # -*- coding:utf-8 -*- value = " a " ret = value.strip() print(ret)
- 分割
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- value = "hello,world" ret = value.split(',') print(ret)
- 长度
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- value = "hello,world" ret = value.__len__() print(ret)
- 索引
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- value = "hello,world" ret = value[0] print(ret)
- 切片
例:
#!/usr/bin/env python # -*- coding:utf-8 -*- value = "hello,world" ret = value[0:6] print(ret)
字符串内建函数
#!/usr/bin/env python # -*- coding:utf-8 -*- """ capitalize() 将字符串的第一个字符转换为大写 """ value = " hello,world " ret = value.capitalize() print(ret) """ center(width, fillchar) 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格 """ ret = value.center(30) print(ret) """ count(str, beg= 0,end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 """ ret = value.count('l') print(ret) """ decode(encoding='UTF-8',errors='strict') 使用指定编码来解码字符串。默认编码为字符串编码 encode(encoding='UTF-8',errors='strict') 以 encoding 指定的编码格式编码字符串 temp = "中文" #解码,需要指定原来是什么编码 temp_unicode = temp.decode('utf-8') #编码,需要指定要编成什么编码 temp_gbk = temp_unicode.encode('gbk') print(temp_gbk) """ """ endswith(suffix, beg=0, end=len(string)) 检查字符串是否以某字符串结尾如果是,返回 True,否则返回 False. """ ret = value.endswith('d') print(ret) """ expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 """ ret = value.expandtabs() print(ret) """ find(str, beg=0 end=len(string)) 检测 str 是否包含在字符串中 中,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1 """ ret = value.find('h') print(ret) """ index(str, beg=0, end=len(string)) 跟find()方法一样,只不过如果str不在字符串中会报一个异常,使用find方法最佳 """ """ isdigit() 如果字符串只包含数字则返回 True 否则返回 False """ ret = value.isdigit() print(ret) """ lstrip() 截掉字符串左边的空格 """ ret = value.lstrip() print(ret) """ rstrip() 删除字符串字符串末尾的空格 """ ret = value.rstrip() print(ret) """ split(str="", num=string.count(str)) num=string.count(str)) 以 str 为分隔符截取字符串 """ ret = value.split(',') print(ret) """ strip([chars]) 去除左右空格 """ ret = value.strip() print(ret) """ title() 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写 """ ret = value.title() print(ret)
python字符串格式化符号:
4.列表
列表中每个位置都分配一个数字,从0开始,依此类推
基本操作:
- 索引
- 切片
- 追加
- 删除
- 长度
- 循环
- 包含
创建列表
#!/usr/bin/env python # -*- coding:utf-8 -*- list = ['a','b']
例:
#!/usr/bin/env python # -*- coding:utf-8 -*-
"""
索引
"""
list = ['a','b'] ret = list[0] print(ret)
#!/usr/bin/env python # -*- coding:utf-8 -*-
"""
切片
"""
list = ['a','b','c'] ret = list[0:2] print(ret)
追加
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 追加 """ list = ['a','b','c'] list.append('d') print(list)
删除
#!/usr/bin/env python # -*- coding:utf-8 -*-
"""
删除索引1
"""
list = ['a','b','c'] print(list) del list[1] print(list)
长度
#!/usr/bin/env python # -*- coding:utf-8 -*- list = ['a','b','c'] ret=list.__len__() print(ret)
循环
#!/usr/bin/env python # -*- coding:utf-8 -*- list = ['a','b','c'] for i in list: print(i)
包含
#!/usr/bin/env python # -*- coding:utf-8 -*- list = ['a','b','c'] list2 = ['d','e'] total = [list + list2] print(total)
列表中内置函数
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 排序 """ list = [1,4,2,3,4,5,10,3] list.sort() print(list) """ list.count(obj) 统计某个元素在列表中出现的次数 """ ret = list.count(3) print(ret) """ list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) """ list2 = [100,101,105] list.extend(list2) print(list) """ list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 """ list.pop() print(list) """ list.remove(obj) 移除列表中某个值的第一个匹配项 """ list.remove(1) print(list) """ list.reverse() 反向列表中元素 """ list.reverse() print(list) """ list.clear() 清空列表 """ list.clear() print(list)
5.元组
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号
创建元组
#!/usr/bin/env python # -*- coding:utf-8 -*- tup = ('a','b','c')
- 索引
- 切片
- 循环
- 长度
- 包含
#!/usr/bin/env python # -*- coding:utf-8 -*- list = ['a', 'b', 'c'] """ tuple(seq) 将列表转换为元组 """ tup = tuple(list) print(tup)
6.字典
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中
创建字典
person = {"name": "liu", 'age': 18}
键必须是唯一的,值不必
常用操作:
- 索引
#!/usr/bin/env python # -*- coding:utf-8 -*- dic = { "name":"mary","age":20 } dic1 = dic["name"] print(dic1)
- 新增
#!/usr/bin/env python # -*- coding:utf-8 -*- dic = { "name":"mary","age":20 } dic["address"] = "beijing" print(dic)
- 删除
#!/usr/bin/env python # -*- coding:utf-8 -*- dic = { "name":"mary","age":20 } dic["address"] = "beijing" del dic["age"] print(dic)
- 键、值、键值对
- 循环
#!/usr/bin/env python # -*- coding:utf-8 -*- dic = { "name":"mary","age":20 } for key,value in dic.items(): print(key,value)
- 长度
#!/usr/bin/env python # -*- coding:utf-8 -*- dic = { "name":"mary","age":20 } print(len(dic))
字典内建函数
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ 清除内容 """ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ 浅拷贝 """ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ 根据key获取值,d是默认值 """ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ 是否有key """ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ 所有项的列表形式 """ """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ 项可迭代 """ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ key可迭代 """ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ value可迭代 """ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ 所有的key列表 """ """ D.keys() -> list of D's keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {'name':'alex', 'age': 18000} [('name','sbsbsb'),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ 所有的值 """ """ D.values() -> list of D's values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ 所有项,只是将内容保存至view对象中 """ """ D.viewitems() -> a set-like object providing a view on D's items """ pass def viewkeys(self): # real signature unknown; restored from __doc__ """ D.viewkeys() -> a set-like object providing a view on D's keys """ pass def viewvalues(self): # real signature unknown; restored from __doc__ """ D.viewvalues() -> an object providing a view on D's values """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, k): # real signature unknown; restored from __doc__ """ D.__contains__(k) -> True if D has a key k, else False """ return False def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None dict
注:一般字符串,只要执行一个功能,会生成一个新内容,原内容不变,追加除外
list,tuple,dict,执行一个功能是原内容进行变化
三.for循环
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串,格式如下
for value in seq: do xx
例
#!/usr/bin/env python # -*- coding:utf-8 -*- list = [1,2,5,7] for i in list: print(i)
也可以break,continue
#!/usr/bin/env python # -*- coding:utf-8 -*- list = [1,2,5,7] for i in list: if i == 5: break print(i)
#!/usr/bin/env python # -*- coding:utf-8 -*- list = [1,2,5,7] for i in list: if i == 5: continue print(i)
2.enumrate
为可迭代的对象添加序号
#!/usr/bin/env python # -*- coding:utf-8 -*- li = [11,22,33] for k,v in enumerate(li, 1): print(k,v)
3.range和xrange
指定范围,生成指定的数字
#!/usr/bin/env python # -*- coding:utf-8 -*- for i in range(10): print(i)
四.练习
列表,字符串,元组,字典之间相互转换
#!/usr/bin/env python # -*- coding:utf-8 -*- st = "hello" li = ["alec", " aric", "Alex", "Tony", "rain"] tu = ("alec", " aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"} #列表转无组 tup = tuple(li) print(tup) #元组转列表 lis = list(tu) print(lis) #字典转列表 tup_list = list(dic.values()) print(tup_list) #str转list str_list = list(st) print(str_list)
2.列表操作
更换列表元素
li = ['a','b'] li[1] = 'c' print(li)
将列表转换为字典的key并按照10开始向后递增
li = ['a','b','c'] dic = {} for key,v in enumerate(li,10): print(key,v) dic[key]=v print(dic)
五.模拟题
1、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 需求:有如下值集合 [11,22,33,44,55,66,77,88,99,90] 将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中 """ list = [11,22,33,44,55,66,77,88,99,90] dic = { "key1": [], "key2": [] } for i in list: if i > 66: dic['key1'].append(i) else: dic['key2'].append(i) print(dic)
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 查找列表中元素,移动空格,并查找以 a或A开头 并且以 c 结尾的所有元素 """ li = ["alec", " Aric", "Alex", "Tony", "rain"] tu = ("alec", " aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"} list1 = list(tu) list2 = list(dic.values()) newlist = li + list1 + list2 for i in newlist: ret = i.strip() if (ret.startswith('a') or ret.startswith('A')) and ret.endswith('c'): print(ret)
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 输出商品列表,用户输入序号,显示用户选中的商品 商品 li = ["手机", "电脑", '鼠标垫', '游艇'] """ li = ["手机", "电脑", '鼠标垫', '游艇'] for key,i in enumerate(li): print(key,i) inp = input("please input your chose:") chose = int(inp) print(li[chose])
功能要求:
- 要求用户输入总资产,例如:2000
- 显示商品列表,让用户根据序号选择商品,加入购物车
- 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
- 附加:可充值、某商品移除购物车
goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "手机", "price": 998}, ]
#!/usr/bin/env python # -*- coding:utf-8 -*-
#version:1.1
""" 功能要求: 要求用户输入总资产,例如:2000 显示商品列表,让用户根据序号选择商品,加入购物车 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。 附加:可充值、某商品移除购物车 """ """ 1.创建空的购物车列表 2.要求用户输入金额资产 3.输入后列出商品列表 4.用户选择商品,加入购物车 5.结算,如果商品价格大于用户总资产提示余额不足,询问是否删除商品 6.结算资金充裕,提示购买成功,显示余额并退出 """ goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "手机", "price": 998}, ] cart ={ "goods_list":[], "goods_prices":[] } #用户输入账户总额 money = int(input("Please enter your assets:")) #列出商品信息 print("Products list:") while True: for key,values in enumerate(goods, 1): for i in range(len(goods)): if key - 1 == i: print(key, goods[i]["name"], goods[i]["price"]) #用户选择商品 producets = int(input("You can select the product you like:")) print("Selecting Goods:",goods[producets-1]["name"],"cost:",goods[producets-1]["price"]) #计算选购此商品后余额 cur_assets = money - goods[producets-1]["price"] if cur_assets > 0: #如果资金充实将商品加入购物车并结算 cart['goods_list'].append(goods[producets-1]["name"]) cart['goods_prices'].append(goods[producets-1]['price']) #print("Your current balance is:", cur_assets, "¥") chose = input("continue,please enter 'c';checked out,enter 'o';show information,enter 'l';quit,enter 'q'") #查看加入购物车商品信息 if chose == 'l': for prod, val in enumerate(cart["goods_list"], 1): print(prod, val) #退出 if chose == "q": print("Thank you") break #继续购物 if chose == "c": continue #结账 if chose == "o": total = (sum(cart['goods_prices'])) if total > money: print("Sorry,your account doesn't have a large enough balance") # 否则就退出程序,并且输出用户本次消费的情况 else: print("Thanks,cost:", total, "¥", "Account balance:", money - total, "¥") break else: print("error,please try agen") else: print("Sorry,your account doesn't have a large enough balance") break
#!/usr/bin/env python # -*- coding:utf-8 -*- #version1.2 goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "手机", "price": 998}, ] #用户输入总资产 money = input("请输入总资产:") asset = int(money) #定义空购物车 cart = {} for i in goods: print(i["name"],i["price"]) while True: i2 = input("请选择商品(y/Y)结算;") #如果选择结算退出循环 if i2.lower() == "y": break #否则继续购物, for item in goods: if item["name"] == i2: name = item["name"] #如果购物车已经有此商品,数量+1 if name in cart.keys(): cart[name]["num"] = cart[name]["num"] + 1 #反之,新增字典 else: cart[name] = {'num': 1,'sigle_price': item["price"]} print(cart) #结账 all_prices = 0 for k,v in cart.items(): n = v['sigle_price'] m = v['num'] all_sum = n * m all_prices = all_prices + all_sum if all_prices > asset: print("余额不足") else: print("消费:",all_prices)
5、用户交互,显示省市县三级联动的选择
dic = { "河北": { "石家庄": ["鹿泉", "藁城", "元氏"], "邯郸": ["永年", "涉县", "磁县"], } "河南": { ... } "山西": { ... } }
#!/usr/bin/env python # -*- coding:utf-8 -*-
#version:1.1
""" 三级联动 """ dic = { "河北":{ "石家庄":["鹿泉", "藁城", "元氏"], "邯郸":["永年", "涉县", "磁县"] }, "河南":{ "郑州":["中原区", "二七区"], "洛阳":["西宫区","洛龙区"] }, "山西":{ "太原":["南城区","北城区"], "大同":["兴和","丰镇"] } } for i in dic: print(i) flag = False for trys in range(3): provinces_name = input("Please select provinces:") if provinces_name in dic: provinces = dic[provinces_name] city = provinces.keys() while True: for citys in city: print(citys) city_name = input("Please enter the city name: ") if city_name in city: area_name = dic[provinces_name][city_name] for i in area_name: print(i) else: print("Please try agen:") continue chose = input("Do you want to quit? quit,enter q;Back to top,enter b.") if chose == "q": print("The application will exits") flag = True break if chose == "b": continue else: print("The information is incorrect,please try agen:") if flag: break else: print("Three times error, the program will exit")
六.知识点补充
1.字符串构造
#!/usr/bin/env python # -*- coding: utf-8 -*- #字符串构造 d = {"name":"Peter","age":20} t = "insert into tb(%s) VALUES (%s)" key_list = [] value_list = [] for k,v in d.items(): key_list.append(k) value_list.append("%%(%s)s" %(k)) print(key_list,",".join(key_list)) print(value_list,','.join(value_list)) sql = t % (','.join(key_list),','.join(value_list)) print(sql)
2.列表推导式
大多数Python开发者知道使用列表推导式。你不熟悉这一点? 一个列表推导式是一个创造列表的简短方式:
>>> some_list = [1, 2, 3, 4, 5] >>> another_list = [ x + 1 for x in some_list ] >>> another_list [2, 3, 4, 5, 6]
从Python 3.1开始(也反向地移植到了Python 2.7),我们可以用同样的方式创建集合和字典:
>>> some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8] >>> even_set = { x for x in some_list if x % 2 == 0 } >>> even_set set([8, 2, 4]) >>> # Dict Comprehensions >>> d = { x: x % 2 == 0 for x in range(1, 11) } >>> d {1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}
第一个例子中,我们用 some_list
建立了一个元素不重复的集合,但只有偶数。第二个字典的例子中展示了一个字典的创建,这个字典的键是1到10(包括10),值是布尔值,指明该键是不是一个偶数。
另一个值得注意的地方是集合的文法,我们可以这么简单的创建一个集合:
>>>my_set = {1, 2, 1, 2, 3, 4} >>> my_set set([1, 2, 3, 4])
3. 使用计数器对象计数
很明显,但很容易遗忘。计数是一个寻常不过的编程任务,而且大多数情形下这不是个难事。不过计数可以更简单。
Python的 collections 库包含一个 dict
的子类,专门解决计数任务:
>>> from collections import Counter >>> c = Counter('hello world') >>> c Counter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1}) >>> c.most_common(2) [('l', 3), ('o', 2)]