mouse 发表于 2018-8-15 07:38:44

6.Python入门到精通

  字符串:格式化
  >>> "{0} love {1}.{2}" .format("I","pyton","com")
  'I love pyton.com'
  >>>
  >>> "{a} love {b}.{c}" .format(a='I',b='python',c='com')
  'I love python.com'
  >>> "{0} love {b}.{c}" .format('I',b='python',c='com')
  'I love python.com'
  >>>
  >>> "{a} love {b}.{0}" .format(a='I',b='python','com')
  SyntaxError: positional argument follows keyword argument
  >>>
  >>> print('\ta')
  a
  >>> print ('\\')
  \
  >>> "`0`" .format("不打印")
  '{0}'
  >>> '{0:.1f}{1}'.format(27.658,'GB')
  '27.7GB'
  >>>

  >>> '%c' % 97
  'a'
  >>> '%c %c %c' % (97,98,99)
  'a b c'
  >>> '%s' % 'I love Python'
  'I love Python'
  >>> '%d + %d = %d' %(4,5,4+5)
  '4 + 5 = 9'
  >>> '%o' % 10
  '12'
  >>> '%x' % 10
  'a'
  >>> '%X' % 10
  'A'
  >>> '%f' % 27.658
  '27.658000'
  >>> '%e' % 27.658
  '2.765800e+01'
  >>> '%E' % 27.658
  '2.765800E+01'
  >>> '%G' % 27.658
  '27.658'
  >>>

  >>> '%f' % 27.658
  '27.658000'
  >>> '%e' % 27.658
  '2.765800e+01'
  >>> '%E' % 27.658
  '2.765800E+01'
  >>> '%G' % 27.658
  '27.658'
  >>> '%5.1f' % 27.658
  ' 27.7'
  >>> '%.2e' % 27.658
  '2.77e+01'
  >>> '%10d' % 5
  '         5'
  >>> '%-10d' % 5
  '5         '
  >>> '%+10d' % 5
  '      +5'
  >>>
  >>> '%#o' % 10
  '0o12'
  >>> '%#X' % 108
  '0X6C'
  >>> '%#d' % 10
  '10'
  >>> '%010d' %5
  '0000000005'
  >>> '%-010d' %5
  '5         '
  >>>

  序列!序列!
  列表、元组和字符串的共同点
  都可以通过索引得到每一个元素
  默认索引值总是从0开始
  可以通过分片的方法得到一个范围内的元素的集合
  有很多共同的操作符(重复操作符、拼接操作符、成员关系操作符)
  >>> help(list)

  Help on>  class list(object)
  |list() -> new empty list
  |list(iterable) -> new list initialized from iterable's items
  |
  |Methods defined here:
  |
  |__add__(self, value, /)
  |      Return self+value.
  |
  |__contains__(self, key, /)
  |      Return key in self.
  |
  |__delitem__(self, key, /)
  |      Delete self.
  |
  |__eq__(self, value, /)
  |      Return self==value.
  |
  |__ge__(self, value, /)
  |      Return self>=value.
  |
  |__getattribute__(self, name, /)
  |      Return getattr(self, name).
  |
  |__getitem__(...)
  |      x.__getitem__(y) <==> x
  |
  |__gt__(self, value, /)
  |      Return self>value.
  |
  |__iadd__(self, value, /)
  |      Implement self+=value.
  |
  |__imul__(self, value, /)
  |      Implement self*=value.
  |
  |__init__(self, /, *args, **kwargs)
  |      Initialize self.See help(type(self)) for accurate signature.
  |
  |__iter__(self, /)
  |      Implement iter(self).
  |
  |__le__(self, value, /)
  |      Return self<=value.
  |
  |__len__(self, /)
  |      Return len(self).
  |
  |__lt__(self, value, /)
  |      Return self<value.
  |
  |__mul__(self, value, /)
  |      Return self*value.n
  |
  |__ne__(self, value, /)
  |      Return self!=value.
  |
  |__new__(*args, **kwargs) from builtins.type
  |      Create and return a new object.See help(type) for accurate signature.
  |
  |__repr__(self, /)
  |      Return repr(self).
  |
  |__reversed__(...)
  |      L.__reversed__() -- return a reverse iterator over the list
  |
  |__rmul__(self, value, /)
  |      Return self*value.
  |
  |__setitem__(self, key, value, /)
  |      Set self to value.
  |
  |__sizeof__(...)

  |      L.__sizeof__() -->  |
  |append(...)
  |      L.append(object) -> None -- append object to end
  |
  |clear(...)
  |      L.clear() -> None -- remove all items from L
  |
  |copy(...)
  |      L.copy() -> list -- a shallow copy of L
  |
  |count(...)
  |      L.count(value) -> integer -- return number of occurrences of value
  |
  |extend(...)
  |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
  |
  |index(...)
  |      L.index(value, ]) -> integer -- return first index of value.
  |      Raises ValueError if the value is not present.
  |
  |insert(...)
  |      L.insert(index, object) -- insert object before index
  |
  |pop(...)
  |      L.pop() -> item -- remove and return item at index (default last).
  |      Raises IndexError if list is empty or index is out of range.
  |
  |remove(...)
  |      L.remove(value) -> None -- remove first occurrence of value.
  |      Raises ValueError if the value is not present.
  |
  |reverse(...)
  |      L.reverse() -- reverse *IN PLACE*
  |
  |sort(...)
  |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
  |
  |----------------------------------------------------------------------
  |Data and other attributes defined here:
  |
  |__hash__ = None
  >>>
  迭代是重复反馈过程活动,其目的通常是为了接近达到所需的目标或结果。
  >>> a = list()
  >>> a
  []
  >>> b = 'I love Pyton'
  >>> b = list(b)
  >>> b
  ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'P', 'y', 't', 'o', 'n']
  >>>
  >>> c = (1,1,2,3,5,8,13,21,34)
  >>> c = list(c)
  >>> c
  
  >>>
  Tuple()把一个可迭代对象转换为元组
  >>> help(tuple)

  Help on>  class tuple(object)
  |tuple() -> empty tuple
  |tuple(iterable) -> tuple initialized from iterable's items
  |
  |If the argument is a tuple, the return value is the same object.
  |
  |Methods defined here:
  |
  |__add__(self, value, /)
  |      Return self+value.
  |
  |__contains__(self, key, /)
  |      Return key in self.
  |
  |__eq__(self, value, /)
  |      Return self==value.
  |
  |__ge__(self, value, /)
  |      Return self>=value.
  |
  |__getattribute__(self, name, /)
  |      Return getattr(self, name).
  |
  |__getitem__(self, key, /)
  |      Return self.
  |
  |__getnewargs__(...)
  |
  |__gt__(self, value, /)
  |      Return self>value.
  |
  |__hash__(self, /)
  |      Return hash(self).
  |
  |__iter__(self, /)
  |      Implement iter(self).
  |
  |__le__(self, value, /)
  |      Return self<=value.
  |
  |__len__(self, /)
  |      Return len(self).
  |
  |__lt__(self, value, /)
  |      Return self<value.
  |
  |__mul__(self, value, /)
  |      Return self*value.n
  |
  |__ne__(self, value, /)
  |      Return self!=value.
  |
  |__new__(*args, **kwargs) from builtins.type
  |      Create and return a new object.See help(type) for accurate signature.
  |
  |__repr__(self, /)
  |      Return repr(self).
  |
  |__rmul__(self, value, /)
  |      Return self*value.
  |
  |count(...)
  |      T.count(value) -> integer -- return number of occurrences of value
  |
  |index(...)
  |      T.index(value, ]) -> integer -- return first index of value.
  |      Raises ValueError if the value is not present.
  >>>
  Str(obj)把obj对象转换为字符串
  >>> len(a)
  0
  >>> len(b)
  12
  >>> b
  ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'P', 'y', 't', 'o', 'n']
  max()返回序列或者参数集合中的最大值
  >>> max(1,2,3,4,5)
  5
  >>> max(b)
  'y'
  >>> numbers =
  >>> max(numbers)
  89
  >>>
  min()返回序列或者参数集合中的最小值
  >>> min(numbers)
  -98
  >>> chars = '1234567890'
  >>> min(chars)
  '0'
  >>> tuple1 = (1,2,3,4,5,6,7,8,9,0)
  >>> min(tuple1)
  0
  >>>
  sum(iterable[,start=0])返回序列iterable和可选参数start的总和
  >>> tuple2 = (3,1,2,3,3,4)
  >>> sum(tuple2)
  16
  >>> sum(tuple2,4)
  20
  >>>
  >>> chars
  '1234567890'
  >>> sum(chars)
  Traceback (most recent call last):
  File "<pyshell#256>", line 1, in <module>
  sum(chars)
  TypeError: unsupported operand type(s) for +: 'int' and 'str'
  >>>
  >>> sorted(numbers)
  [-98, 0, 1, 13, 18, 32, 34, 67, 89]
  >>> reversed(numbers)
  <list_reverseiterator object at 0x0000000002DDCFD0>
  >>> list(reversed(numbers))
  
  >>> enumerate(numbers)
  <enumerate object at 0x0000000002E0F750>
  >>> list(enumerate(numbers))
  [(0, 1), (1, 18), (2, 13), (3, 0), (4, -98), (5, 34), (6, 67), (7, 89), (8, 32)]
  >>> a =
  >>> b =
  >>> zip (a,b)
  <zip object at 0x0000000002E09648>
  >>> list(zip(a,b))
  [(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]
  >>>
  函数:Python的乐高积木
  函数
  对象
  模块

  >>> def MySecondFunction(name):
  print(name + '我爱你')
  >>> MySecondFunction('jm')
  jm我爱你
  >>> MySecondFunction('j')
  j我爱你
  >>> def add(num1 , num2):
  result = num1 + num2
  print(result)
  >>> def add(num1 , num2):
  result = num1 + num2
  print(result)
  >>> add(1 , 2)
  3
  >>> def add(num1 , num2):
  return (num1 + num2)
  >>> print (add(5 , 6))
  11
  >>> print (11)
  11
  >>>
  形参和实参
  >>> def MyFirstFunction(name):
  '函数定义过程中的name是叫形参'
  #因为Ta只是一个形式,表示占据一个参数位置
  print('传递进来的' + name + '叫做实参,因为Ta是具体的参数值!')
  >>> MyFirstFunction('jm')
  传递进来的jm叫做实参,因为Ta是具体的参数值!
  形式参数(parameter)实际参数(argument)
  函数文档
  >>> def MyFirstFunction(name):
  '函数定义过程中的name是叫形参'
  #因为Ta只是一个形式,表示占据一个参数位置
  print('传递进来的' + name + '叫做实参,因为Ta是具体的参数值!')
  >>> MyFirstFunction('jm')
  传递进来的jm叫做实参,因为Ta是具体的参数值!
  >>> MyFirstFunction.__doc__
  '函数定义过程中的name是叫形参'
  >>>
  >>> help(MyFirstFunction)
  Help on function MyFirstFunction in module __main__:
  MyFirstFunction(name)
  函数定义过程中的name是叫形参
  >>> print .__doc__
  "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile:a file-like object (stream); defaults to the current sys.stdout.\nsep:   string inserted between values, default a space.\nend:   string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
  >>> help(print)
  Help on built-in function print in module builtins:
  print(...)
  print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  Prints the values to a stream, or to sys.stdout by default.
  Optional keyword arguments:
  file:a file-like object (stream); defaults to the current sys.stdout.
  sep:   string inserted between values, default a space.
  end:   string appended after the last value, default a newline.
  flush: whether to forcibly flush the stream.
  >>>
  关键字参数
  >>> def SaySome(name , words):
  print(name + '->' + words)
  >>> SaySome('jm','让编程改变世界!')
  jm->让编程改变世界!
  >>> SaySome('让编程改变世界!','jm')
  让编程改变世界!->jm
  >>> SaySome(words='让编程改变世界!',name='jm')
  jm->让编程改变世界!
  >>>
  默认参数
  >>> def SaySome(name='jm',words='让编程改变世界!'):
  print(name + '->' + words)
  >>> SaySome()
  jm->让编程改变世界!
  >>> SaySome('j')
  j->让编程改变世界!
  >>> SaySome('j','m')
  j->m
  >>>
  收集参数
  >>> def test(*params):
  print('参数的长度是:',len(params));
  print('第二参数是:',params);
  >>> test(1,'jm',3,14,5,6,7,8,9)
  参数的长度是: 9
  第二参数是: jm
  >>>
  >>> def test(*params,exp):
  print('参数的长度是:',len(params),exp);
  print('第二参数是:',params);
  >>> test(1,'jm',3,14,5,6,7,8,9)
  Traceback (most recent call last):
  File "<pyshell#321>", line 1, in <module>
  test(1,'jm',3,14,5,6,7,8,9)
  TypeError: test() missing 1 required keyword-only argument: 'exp'
  >>> test(1,'jm',3,14,5,6,7,8,exp = 9)
  参数的长度是: 8 9
  第二参数是: jm
  >>>
  函数与过程
  >> def hello():
  print("Hello python")
  >>> temp = hello()
  Hello python
  >>> temp
  >>>
  >>> print(temp)
  None
  >>>
  >>> type(temp)
  <class 'NoneType'>
  >>>
  再谈谈返回值
  >>> def back():
  return
  >>> back()
  
  >>> def back():
  return 1,'a',3.14
  >>> back()
  (1, 'a', 3.14)
  >>>
  我的地盘听我的
  def discounts(price, rate):
  final_price = price * rate
  old_price = 88 #这里试图修改全局变量
  print('修改后old_price的值是:', old_price)
  return final_price
  old_price = float(input('请输入原价:'))
  rate = float(input('请输入折扣率:'))
  new_price = discounts(old_price, rate)
  print('修改后old_price的值是:', old_price)
  print('打折后价格是:', new_price)
  函数:内嵌函数和闭包
  >>> count = 5
  >>> def MyFun():
  count = 10
  print(10)
  >>> MyFun()
  10
  >>> print (count)
  5
  >>>
  >>> def MyFun():
  global count
  count = 10
  print (10)
  >>> MyFun()
  10
  >>> print(count)
  10
  >>>
  内嵌函数
  >>> def fun1():
  print('fun1()正在被调用...')
  def fun2():
  print('fun2()正在被调用...')
  fun2()
  >>> fun1()
  fun1()正在被调用...
  fun2()正在被调用...
  >>>
  闭包
  >>> def FunX(x):
  def FunY(y):
  return x * y
  return FunY
  >>> i=FunX(8)
  >>> i
  <function FunX.<locals>.FunY at 0x0000000002E406A8>
  >>> type(i)
  <class 'function'>
  >>> i(5)
  40
  >>> FunX(8)(5)
  40
  >>>
  >>> FunY(5)
  Traceback (most recent call last):
  File "<pyshell#374>", line 1, in <module>
  FunY(5)
  NameError: name 'FunY' is not defined
  >>>
  >>> def Fun1():
  x=5
  def Fun2():
  x *= x
  return x
  return Fun2()
  >>> Fun1()
  Traceback (most recent call last):
  File "<pyshell#386>", line 1, in <module>
  Fun1()
  File "<pyshell#385>", line 6, in Fun1
  return Fun2()
  File "<pyshell#385>", line 4, in Fun2
  x *= x
  UnboundLocalError: local variable 'x' referenced before assignment
  >>>
  >>> def Fun1():
  x =
  def Fun2():
  x *= x
  return x
  return Fun2()
  >>> Fun1()
  25
  >>>
  >>> def Fun1():
  x = 5
  def Fun2():
  nonlocal x
  x *= x
  return x
  return Fun2()
  >>> Fun1()
  25
  >>>
  函数:lambda表达式
  >>> def ds(x):
  return 2* x + 1
  >>> ds(5)
  11
  >>> lambda x : 2 * x + 1
  <function <lambda> at 0x0000000002E40AE8>
  >>> g = lambda x : 2 * x + 1
  >>> g(5)
  11
  >>> def add(x,y):
  return x + y
  >>> add(3,4)
  7
  >>> lambda x , y : x + y
  <function <lambda> at 0x0000000002E1DF28>
  >>> g = lambda x , y : x + y
  >>> g(3 , 4)
  7
  >>>
  l Python写一些执行脚本时,使用lambda就可以省下定义函数过程,比如说我们只是需要写个简单的脚本来管理服务器时间,我们就不需要专门定义一个函数然后再写调用,使用lambda就可以使得代码更加精简。
  l 对于一些比较抽象并且整个程序执行下来只需要调用一两次的函数,有时候给函数起个名字也是比较头疼的问题,使用lambda就不需要考虑命名的问题了。
  l 简化代码的可读性,由于普通的屌丝函数阅读经常要跳到开头def定义部分,使用lambda函数可以省去这样的步骤。
  两个牛逼的BIF
  >>> help(filter)

  Help on>  class filter(object)
  |filter(function or None, iterable) --> filter object
  |
  |Return an iterator yielding those items of iterable for which function(item)
  |is true. If function is None, return the items that are true.
  |
  |Methods defined here:
  |
  |__getattribute__(self, name, /)
  |      Return getattr(self, name).
  |
  |__iter__(self, /)
  |      Implement iter(self).
  |
  |__new__(*args, **kwargs) from builtins.type
  |      Create and return a new object.See help(type) for accurate signature.
  |
  |__next__(self, /)
  |      Implement next(self).
  |
  |__reduce__(...)
  |      Return state information for pickling.
  >>> filter(None,)
  <filter object at 0x0000000002E41EB8>
  >>> list(filter(None,))
  
  >>> def odd(x):
  return x % 2
  >>> temp = range(10)
  >>> show = filter(odd,temp)
  >>> list(show)
  
  >>> list(filter(lambda x : x % 2, range(10)))
  
  >>>
  >>> list(map(lambda x : x * 2, range(10)))
  
  >>>
  
页: [1]
查看完整版本: 6.Python入门到精通