python之路第二篇(基础篇)

入门知识:

一、关于作用域:

对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用。

if 10 == 10:
name = 'allen'
print name

以下结论对吗?

外层变量,可以被内层变量使用
内层变量,无法被外层变量使用 以上结论,对于其他语言适用,对于python 不适用
** 记住:python,只要内存里存在,则就能适用 (栈 )

二、三元运算:

1)、普通循环:

if name == “test”:
name = “坏人”
print name
else:
name = “好人”
print name

2)、以下是三元运算:

格式:

name = 值
name = 值1 if 条件 else 值2
如果条件为真:result = 值1
如果条件为假:result = 值2 name = ‘坏人’ if name == test else “好人” #用户输入内容,得到值 #运算,得结果:如果用户输入 Allen, 坏人,否则,好人

python基础

对于Python,一切事物都是对象,对象基于类创建

一、整型:

如:1,2,3,4,5

学会查看帮助:

type(类型名) 查看对象的类型

dir(类型名) 查看类中提供的所有功能

help(类型名) 查看类中所有详细的功能

help( 类型名.功能名) 查看类中某功能的详细

内置方法,非内置方法

>>> dir(list)

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

类中的方法:

方法: 内置方法,可能有多种执行方法,

>>> n1 = 1
>>> dir(n1) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

以下都是整型一些方法:

add:求和:

>>> n2 = 2
>>> n1 + n2
3
>>> n1.__add__(n2)
3

abs 求绝对值

>>> n1 = -8
>>> n1.__abs__()返回绝对值
8
>>> abs(-9)
9

int:整型转换:

>>> i = 10
>>> i = int(10)
>>> i
10 >>> i = int("10",base=2)
>>> i
2
>>> i = int("11",base=2) (2代表二进制)
>>> i
3 >>> i = int("F",base=16)
>>> i
15

cmp:两个数比较:

>>> age = 20
>>> age.__cmp__(18) 比较两个数大小
1
>>> age.__cmp__(22)
-1 >>> cmp(18,20)
-1
>>> cmp(22,20)
1

coerce:商和余数,强制生成一个元组:

>>> i1 = 10
>>> i1.__coerce__(2)
(10, 2) (强制生成一个元组)

divmod:分页,相除,得到商和余数组成的元组

>>> a = 98
>>> a.__divmod__(10)
(9, 8) #相除,得到商和余数组成的数组,这个一定要会

float:转换为浮点类型

>>> type(a)
<type 'int'>
>>> float(a) 转换为浮点类型
98.0
>>> a.__float__()
98.0

floordiv :地板浮点型

>>> 5 /2
2
>>> 5 // 2
2
>>> 5.0/2
2.5
>>> 5.0//2
2.0

hash:

如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。

>>> ha = "Allen"
>>> ha.__hash__()
85081331482274937 >>> h1 = 18
>>> h1.__hash__()
18

hex:16进制表示

>>> age = 18
>>> age.__hex__()
‘0x12'

oct:返回8进制表示:

>>> age = 18
>>> age.__oct__()
'022'

index:用于切片,数字表示无意义

init:

构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """

>>> i = 10
>>> i = int(10)

int:转换为整型

>>> a = "2"
>>> type(a)
<type 'str'>
>>> a = int(a)
>>> type(a)
<type 'int'>

pow:幂次方:

>>> pow(2,4)
16
如下两个面试可能会遇到(repr,str):
repr
"""转化为解释器可读取的形式 “"" str
"""转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""

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"""

二、字符串:

str:转换成str类型:

>>> s = str("abc")

capitalize:首字母变大写:

>>> s.capitalize()
‘Abc'

center:内容居中:

>>> name = "Allen"
>>> name.center(20)
' Allen '
>>> name.center(20,"*”) """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 “"" '*******Allen********’

count:子序列个数:

>>> name = "skkkdssslklsiks"
>>> name.count('s',0,10) """ 子序列个数 """
4
>>> name.count('s',0,15)
6
>>> name.count('s',0,20)
6

三种字符编码转换知识:

unicode、 utf-8、 gbk

utf-8 —> unicode(通过解码方法转换:decode)
gbk —> unicode (通过解码方法转换:decode)
unicode —> utf-8 (通过编码方法转换:encode)
unicode —> gbk (通过编码方法转换:encode)
编码转换:

解码:

>>> str2 = “好"
>>> str2
'\xe5\xa5\xbd’ >>> print str2.decode('utf-8')

>>> print str2.decode('utf-8').encode('gbk')

endswith:以...结束:

>>> a = "backend www.yyh.com"
>>> a.endswith('com')
True

startswith:以...开始:

>>> a.startswith('backend')
True

expandtabs:将tab转换成空格,默认一个tab转换成8个空格

>>> name = 'hi   allen'
>>> name.expandtabs(1)
'hi allen' >>> name.expandtabs(2) #这里2,代表转换成2个空格
'hi allen’
>>> jj = name.expandtabs(2)
>>> len(jj)
10

find:找子序列位置,如果没找到,返回 -1

>>> name = ‘Allen'
>>> name.find('l’) """ 寻找子序列位置,如果没找到,则异常 “""
1
>>> name = 'Allen'
>>> name.find('a')
-1

find , index 区别:

find 找不到不会报错,index,找不到会报错

>>> name = "haowwss"
>>> name.find('s',0,4)
-1 >>> name.index('s',0,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> name.index('s',0,10) """ 子序列位置,如果没找到,则返回-1 """
5

字符串格式化:

方法一:
>>> name = 'I am {0},age {1}’
>>> name
'I am {0},age {1}'
方法二:

format:字符串格式化

1)传入字符串:

>>> name.format('Allen',25)  """ 字符串格式化 “”"
'I am Allen,age 25'
>>> name = 'I am {ss},age {dd}'
>>> name.format(ss="Allen",dd=26)
'I am Allen,age 26’ 2)传入一个列表: >>> li = [1111,3333]
>>> name = 'I am {0},age {1}’
>>> name.format(*li) (传列表加一个“*”)
'I am 1111,age 3333’ 3)传入一个字典: name = 'I am {ss},age {dd}’
>>> dic = {'ss':111,'dd':333}
>>> name.format(**dic)
'I am 111,age 333’

isalnum:是否是字母和数字

>>> a
‘howareyou’
>>> a.isalnum()
True
>>> a = "__"
>>> a.isalnum()
False
>>> a = '123'
>>> a.isalnum()
True

isalpha:是否是字母

>>> a
'123'
>>> a.isalpha()
False
>>> a = 'allen'
>>> a.isalpha()
True

isdigit:是否是数字

>>> a = '123'
>>> a.isdigit()
True >>> a = 'allen'
>>> a.isdigit()
False

islower:是否小写

>>> a = 'allen'
>>> a.islower()
True
>>> a = 'Allen'
>>> a.islower()
False

istitle:是否是标题

>>> name = "Hello Allen"
>>> name.istitle()
True
>>> name = "Hello allen"
>>> name.istitle()
False

swapcase:大小写转换

>>> name = "Hello allen"
>>> name.swapcase()
'hELLO ALLEN’

split:分隔:

>>> name.split('l’)
['He', '', 'o a', '', 'en']
>>> name.rsplit('l')
['He', '', 'o a', '', 'en’]

python 字符串方法源码:

def isupper(self):
"""
S.isupper() -> bool Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
"""
return False def join(self, iterable):
""" 连接 """
"""
S.join(iterable) -> string Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return "" def ljust(self, width, fillchar=None):
""" 内容左对齐,右侧填充 """
"""
S.ljust(width[, fillchar]) -> string Return S left-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
return "" def lower(self):
""" 变小写 """
"""
S.lower() -> string Return a copy of the string S converted to lowercase.
"""
return "" def lstrip(self, chars=None):
""" 移除左侧空白 """
"""
S.lstrip([chars]) -> string or unicode Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def partition(self, sep):
""" 分割,前,中,后三部分 """
"""
S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
"""
pass def replace(self, old, new, count=None):
""" 替换 """
"""
S.replace(old, new[, count]) -> string Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
"""
return "" def rfind(self, sub, start=None, end=None):
"""
S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.
"""
return 0 def rindex(self, sub, start=None, end=None):
"""
S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found.
"""
return 0 def rjust(self, width, fillchar=None):
"""
S.rjust(width[, fillchar]) -> string Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return "" def rpartition(self, sep):
"""
S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
"""
pass def rsplit(self, sep=None, maxsplit=None):
"""
S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.
"""
return [] def rstrip(self, chars=None):
"""
S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def split(self, sep=None, maxsplit=None):
""" 分割, maxsplit最多分割几次 """
"""
S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
"""
return [] def splitlines(self, keepends=False):
""" 根据换行分割 """
"""
S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
return [] def startswith(self, prefix, start=None, end=None):
""" 是否起始 """
"""
S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
"""
return False def strip(self, chars=None):
""" 移除两段空白 """
"""
S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def swapcase(self):
""" 大写变小写,小写变大写 """
"""
S.swapcase() -> string Return a copy of the string S with uppercase characters
converted to lowercase and vice versa.
"""
return "" def title(self):
"""
S.title() -> string Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.
"""
return "" def translate(self, table, deletechars=None):
"""
转换,需要先做一个对应表,最后一个表示删除字符集合
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"
print str.translate(trantab, 'xm')
""" """
S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256 or None.
If the table argument is None, no translation is applied and
the operation simply removes the characters in deletechars.
"""
return "" def upper(self):
"""
S.upper() -> string Return a copy of the string S converted to uppercase.
"""
return "" def zfill(self, width):
"""方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
"""
S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
"""
return "" def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
pass def _formatter_parser(self, *args, **kwargs): # real signature unknown
pass def __add__(self, y):
""" x.__add__(y) <==> x+y """
pass def __contains__(self, y):
""" x.__contains__(y) <==> y in x """
pass def __eq__(self, y):
""" x.__eq__(y) <==> x==y """
pass def __format__(self, format_spec):
"""
S.__format__(format_spec) -> string Return a formatted version of S as described by format_spec.
"""
return "" def __getattribute__(self, name):
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y):
""" x.__getitem__(y) <==> x[y] """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __getslice__(self, i, j):
"""
x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported.
"""
pass def __ge__(self, y):
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y):
""" x.__gt__(y) <==> x>y """
pass def __hash__(self):
""" x.__hash__() <==> hash(x) """
pass def __init__(self, string=''): # known special case of str.__init__
"""
str(object='') -> string Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
# (copied from class doc)
"""
pass def __len__(self):
""" x.__len__() <==> len(x) """
pass def __le__(self, y):
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y):
""" x.__lt__(y) <==> x<y """
pass def __mod__(self, y):
""" x.__mod__(y) <==> x%y """
pass def __mul__(self, n):
""" x.__mul__(n) <==> x*n """
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 __ne__(self, y):
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self):
""" x.__repr__() <==> repr(x) """
pass def __rmod__(self, y):
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, n):
""" x.__rmul__(n) <==> n*x """
pass def __sizeof__(self):
""" S.__sizeof__() -> size of S in memory, in bytes """
pass def __str__(self):
""" x.__str__() <==> str(x) """
pass

三、列表:常用的几个方法

以下方法需要学会:

append:追加到一个列表

count:次数

extend:添加

index:索引值,即下标

insert:插入

pop:弹出

remove:删除

reverse:翻转

sort:排序

四、元组

count:次数

>>> a = (1,2,3,4,1,2,3,4)
>>> a.count(2)
2

index:索引值,下标

>>> tu = ("a",'b','c')
>>> tu.index('a')
0

五、字典

字典取值:
>>> dic = {'allen':1234,'yyh':123}
>>> dic
{'allen': 1234, 'yyh': 123}
>>> dic['allen']
1234

get:get方法得到value,不存在返回None

>>> dic.get('kk')
>>> print dic.get('kk’)
None
>>> print dic.get('kk','OK’) #写上OK,则返回OK
OK
>>> print dic.get('kk','TT')
TT
以下方法需要学会
clear:清除内容
copy:浅拷贝
fromkeys:生成字典
has_key:是否有key
get:根据key获取值
items:所有项的列表形式
iteritems:项可迭代
keys:所有的key列表
iterkeys:key可迭代
itervalues:value可迭代
pop:获取并在字典中移除
popitem:获取并在字典中移除(从头开始删除)
del:删除元素
setdefault (不存在则创建,存在则不创建)
update:更新
values:所有项,只是将内容保存至view对象中
cmp:比较 name_dic= {1:11,2:22}
>>> type(name_dic) is dict
True >>> a = {}
>>> a.fromkeys([12,32],'t')
{32: 't', 12: 't’}

六、set集合:

set是一个无序且不重复的元素集合

功能:去重 & | ^ -

issubset  查看是否是某个集合的子集

issuperset 查看是否是某个集合的父集
以下方法多加练习:
add:添加
clear:清除
copy:浅copy
difference:
difference_update:删除当前set中的所有包含在 new set 里的元素
discard:移除元素
intersection:取交集,新创建一个set
intersection_update:取交集,修改原来set "
isdisjoint:如果没有交集,返回true
issubset:是否是子集
issuperset:是否是父集
pop:移除
remove:移除
symmetric_difference:差集,创建新对象
symmetric_difference_update:差集,改变原来
union:并集
update:更新
and
cmp

练习:寻找差异

数据库中原有
old_dict = {
"#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
"#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
"#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
}
cmdb 新汇报的数据
new_dict = {
"#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
"#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
"#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
} 需要删除:?
需要新建:?
需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新

代码如下:

old_set = set(old_dict.keys())
update_list = list(old_set.intersection(new_dict.keys())) new_list = []
del_list = [] for i in new_dict.keys():
if i not in update_list:
new_list.append(i) for i in old_dict.keys():
if i not in update_list:
del_list.append(i) print update_list,new_list,del_list
collection系列:

1)计数器:Counter

Counter是对字典类型的补充,用于追踪值的出现次数

具备字典的所有功能 + 自己的功能

c = Counter('abcdeabcdabcaba')
print c
输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

2)有序字典

orderdDict是对字典类型的补充,他记住了字典元素添加的顺序

3默认字典

defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。

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

作业:

1.打印购物车列表

  死循环
输入一共多少钱
iphone 6s
mac
输入要买的:1
已把【iphone】加入购物车,还有多少钱
最后退出
打印已买的商品 (第二次输入不需要输入工资,相当于存入文件) 2.开发一个简单的计算器程序
  *实现对加减乘除、括号优先级的解析,并实现正确运算 (如果用到递归会有A+) 3*5/ -2 - (8 * 3/(20+3/2-5) +4 /(3-2)* -3) = 3

更多链接:http://www.cnblogs.com/wupeiqi/articles/4911365.html

上一篇:git修改历史记录


下一篇:Using MongoDB with Web API and ASP.NET Core