设为首页 收藏本站
查看: 1783|回复: 0

[经验分享] 6.Python入门到精通

[复制链接]

尚未签到

发表于 2018-8-15 07:38:44 | 显示全部楼层 |阅读模式
  字符串:格式化
  >>> "{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'
  >>>
DSC0000.png

  >>> '%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'
  >>>
DSC0001.png

  >>> '%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         '
  >>>
DSC0002.png

  序列!序列!
  列表、元组和字符串的共同点
  都可以通过索引得到每一个元素
  默认索引值总是从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[key].
  |
  |  __eq__(self, value, /)
  |      Return self==value.
  |
  |  __ge__(self, value, /)
  |      Return self>=value.
  |
  |  __getattribute__(self, name, /)
  |      Return getattr(self, name).
  |
  |  __getitem__(...)
  |      x.__getitem__(y) <==> x[y]
  |
  |  __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[key] 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, [start, [stop]]) -> 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([index]) -> 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
  [1, 1, 2, 3, 5, 8, 13, 21, 34]
  >>>
  Tuple([iterable])把一个可迭代对象转换为元组
  >>> 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[key].
  |
  |  __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, [start, [stop]]) -> 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 = [1,18,13,0,-98,34,67,89,32]
  >>> 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))
  [32, 89, 67, 34, -98, 0, 13, 18, 1]
  >>> 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 = [1,2,3,4,5,6,7,8]
  >>> b = [4,5,6,7,8]
  >>> zip (a,b)
  <zip object at 0x0000000002E09648>
  >>> list(zip(a,b))
  [(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]
  >>>
  函数:Python的乐高积木
  函数
  对象
  模块
DSC0003.png

  >>> 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[1]);
  >>> test(1,'jm',3,14,5,6,7,8,9)
  参数的长度是: 9
  第二参数是: jm
  >>>
  >>> def test(*params,exp):
  print('参数的长度是:',len(params),exp);
  print('第二参数是:',params[1]);
  >>> 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 [1,'a',3.14]
  >>> back()
  [1, 'a', 3.14]
  >>> 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 = [5]
  def Fun2():
  x[0] *= x[0]
  return x[0]
  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,[1,0,False,True])
  <filter object at 0x0000000002E41EB8>
  >>> list(filter(None,[1,0,False,True]))
  [1, True]
  >>> def odd(x):
  return x % 2
  >>> temp = range(10)
  >>> show = filter(odd,temp)
  >>> list(show)
  [1, 3, 5, 7, 9]
  >>> list(filter(lambda x : x % 2, range(10)))
  [1, 3, 5, 7, 9]
  >>>
  >>> list(map(lambda x : x * 2, range(10)))
  [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  >>>
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-551902-1-1.html 上篇帖子: 云计算与数据科学:Microsoft Azure 机器学习与Python 简介 下篇帖子: 7.Python入门到精通
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表