python数据类型详解及列表字典集合推导式详解

一.运算符

Python语言支持以下类型的运算符:

  • 算术运算符

python数据类型详解及列表字典集合推导式详解

如:

#!/usr/bin/env python
# -*- coding:utf-8 -*- a = 5
b = 6
print(a + b)
  • 比较运算符

python数据类型详解及列表字典集合推导式详解

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*- a = 5
b = 6
if a < b:
print(True)
else:
print(False)
  • 赋值运算符

python数据类型详解及列表字典集合推导式详解

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*- a = 5
b = a
print(b)
  • 逻辑运算符

python数据类型详解及列表字典集合推导式详解

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*- a = 5
b = 6
if a >4 and b < 10:
print(True)
else:
print(False)
  • 成员运算符

python数据类型详解及列表字典集合推导式详解

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
value = "a"
list = ['a','b'] if value in list:
print(True)

二.数据类型

  1. 数字

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字符串格式化符号:

aaarticlea/png;base64,iVBORw0KGgoA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L6UiYNg093V80WS3OKOfRsFxCih5guMTt38wePP3YkD4MtwrSJZfAi+ene+OB+2SLbuQHJWbh90wyWYuYP3ZztatwMyOzb/sl0ySI3RRlcHCc7e4qjj8zkB+NIoElTxcX5qk59ZuxNtO1kmp+dpNuMGA3bXGh3j6mKLU5Sc71efzD8OtjU/V8HZXiy2eL49ZABfg4sWSfsZ6vPudJ5wj2QUB0euZiYggr3q1sDi1XbOXl1mdQdG6x58V2fObXwe2oOd71W8WLAAgK/HtYpkGtwlHj3GET7gT20y4yTn4MXzwQw6XyAokvmDxfOrGz3xMJNDxTvWHni74ui8dRcLDgTAl+FyRTKtfX/mg+8sPs5PbUYLdJfPzIVBZMSbaCfpdvX4SJO1MR+tu0xwXItnVq9C/DhTJO1+KhLgglyuSFZnER98Z/HR7pGsTvCLZw4WSXf+7k7So21ldjhYZrSt0epbey45SKZIgjEVCXAdFMk0bfxcRpJPXSSZWTa+BzBteYMdLJLMPgQDtrco2ldbkpto9211n7uL+YsJfHmuVSTBx2j8uYwdfKgiSb6Uua8wX6x9z4xm1nj8+bwbvxvbV+N9CE5du2/xgSerJT60YGfixfzdBL481yqSET7sKjhSJPFkvGmt4PnFq6NIXZ1ru7u3eNyOn9mH0eCre9LdsSBiFgu3KwYnJN7n7la6468usDoggE+NIlmf57AP/6c9AEAeRYIqFAkAII8iQRWKBACQR5GgCkUCAMijSFCFIgEA5FEkqEKRAADyKBJUoUgAAHkUCapQJACAPIoEVSgSAEAeRYIqFAkAII8iQRWKBACQR5GgCkUCAMijSFCFIgEA5Pkza/w/2AC8++BzgukAAAAASUVORK5CYII=" alt="" />

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)
2、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}\
#!/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)
 
3、输出商品列表,用户输入序号,显示用户选中的商品
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']
#!/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])
4、购物车

功能要求:

  • 要求用户输入总资产,例如: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)]
上一篇:extJs学习基础 容器的介绍


下一篇:bug解决: Cause: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 6; 不允许有匹配 “[xX][mM][lL]“ 的