[关闭]
@guoxs 2016-03-06T08:17:15.000000Z 字数 6649 阅读 2718

python 类型与字符串

python


python是一种解释型、面向对象,动态数据类型的高级程序语言。

  1. //精度高,执行时间长
  2. from decimal import Decimal as D

类型

  1. >>> type(a)
  2. <type 'int'>
  3. >>> a = "gh"
  4. >>> type(a)
  5. <type 'str'>
  6. >>> a=[1,2,3,4]
  7. >>> dir(a)
  8. ['__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']
  9. >>> a.count(3)
  10. 1
  11. >>> a = "dfgfht"
  12. >>> a.count("d")
  13. 1
  14. >>> a.__class__
  15. <type 'str'>
  16. >>> a.__doc__
  17. "str(object='') -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object."
  18. >>> a = 3.4
  19. >>> type(a)
  20. <type 'float'>
  21. >>> 0.3*3
  22. 0.8999999999999999
  23. >>> print(0.3*3)
  24. 0.9
  25. >>> 0.3/3
  26. 0.09999999999999999
  27. >>> 10/3
  28. 3
  29. >>> 10.0/3
  30. 3.3333333333333335
  31. >>> from decimal import Decimal as D
  32. >>> D(0.3)*D(0.9)
  33. Decimal('0.2699999999999999966693309261')

耗时比较

  1. $ python -mtimeit -s "from decimal import Decimal as D" "D('1.2')+D('3.4')"
  2. 10000 loops, best of 3: 28.5 usec per loop
  3. $ python -mtimeit -s "from decimal import Decimal as D" "1.2+3.4"
  4. 100000000 loops, best of 3: 0.0172 usec per loop
  5. $ python -mtimeit -s "from decimal import Decimal as D" "float('1.2')+float('3.4')"
  6. 1000000 loops, best of 3: 0.494 usec per loop

常用的库

math 和 random

  1. import math
  2. //π
  3. math.pi
  4. //平方根
  5. math.sqrt()
  6. //对数
  7. math.log10()
  8. //x^y
  9. math.pow(x,y)
  10. //!x
  11. math.factorial(x)
  12. import random
  13. //产生一个[0,1]的浮点数
  14. random.random()
  15. //从列表里等概率随机选择一个
  16. random.choice([1,2,3,4])
  17. //a-b之间整数随机取一个
  18. random.randint(a,b)
  19. //返回a~b之间均匀分布的随机数,浮点数
  20. random.uniform(a,b)
  21. //高斯分布,(均值,方差)
  22. random.gauss(mu,lamda)
  1. >>> import math
  2. >>> math.factorial(5)
  3. 120
  4. >>> math.pi
  5. 3.141592653589793
  6. >>> dir(math)
  7. ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
  8. >>> help(math)
  9. ……

numpy 和 scipy

numpy

scipy

字符串

  1. >>> s = "use python do something"
  2. >>> s[1]
  3. 's'
  4. >>> s[-1]
  5. 'g'
  6. >>> s[1:3]
  7. 'se'
  8. >>> s[1:6:2] //[start,stop,step]
  9. 's y'
  10. >>> s[1:]
  11. 'se python do something'
  12. >>> s[:-1]
  13. 'use python do somethin'
  14. >>> s[:]
  15. 'use python do something'

常用方法集合

  1. >>> "let us" + s,s*2
  2. ('let ususe python do something', 'use python do somethinguse python do something')
  3. >>> s.upper()
  4. 'USE PYTHON DO SOMETHING'
  5. >>> s.find("pa")
  6. -1
  7. >>> s.replace("python","java")
  8. 'use java do something'
  9. >>> print "%s like %s" %("we","python")
  10. we like python
  11. >>> a = s.split(" ")
  12. >>> a
  13. ['use', 'python', 'do', 'something']
  14. >>> b = ", ".join(a)
  15. >>> b
  16. 'use, python, do, something'
  17. >>> s[0:4]*5
  18. 'use use use use use '
  19. >>> s = " life is short, we use python! "
  20. >>> a = s.split(",")
  21. >>> a[1]
  22. ' we use python! '
  23. >>> a[1].strip()
  24. 'we use python!'
  1. //转义
  2. >>> s="C:\newpython"
  3. >>> print s
  4. C:
  5. ewpython
  6. >>> len(s)
  7. 11
  8. >>> s = r"C:\newpython"
  9. >>> print s
  10. C:\newpython

re 模块

Regular expression

编译选项

  1. import re
  2. text = 'c++ python2 python3 perl ruby lua java javascript php4 php5 c'
  3. #match,search,findall,split,sub
  4. re.match(r'java',text) #none(第一个不是“java”)
  5. re.search(r'java',text) #<_sre.SRE_Match object at 0x00000000031046B0>
  6. re.match(r'c++',text) #error
  7. re.match(r'c\+\+',text) #<_sre.SRE_Match object at 0x00000000031941D0>
  8. print re.findall(r'python',text) #['python', 'python']
  9. print re.split(r' perl ',text) #['c++ python2 python3', 'ruby lua java javascript php4 php5 c']
  10. print re.sub(r'ruby','fortran',text) #c++ python2 python3 perl fortran lua java javascript php4 php5 c
  11. # ^ start
  12. # $ end
  13. # . except \n
  14. print re.findall(r'^c..',text) #['c++']
  15. print re.findall(r'c+',text) #['c', 'c', 'c']
  16. print re.findall(r'c\++',text) #['c++']
  17. print re.findall(r'c$',text) #['c']
  18. # + 1-inf
  19. # * 0-inf
  20. # ? 0-1,
  21. # [] or
  22. # {} repeat
  23. # [^] not
  24. print re.findall(r'p+',text)
  25. #['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p']
  26. print re.findall(r'p[a-zA-Z]+',text) #{1,}
  27. #['python', 'python', 'perl', 'pt', 'php', 'php']
  28. print re.findall(r'p[a-zA-Z]*',text) #{0,}
  29. #['python', 'python', 'perl', 'pt', 'php', 'php']
  30. print re.findall(r'p[a-zA-Z]?',text) #{0,1}
  31. #['py', 'py', 'pe', 'pt', 'ph', 'p', 'ph', 'p']
  32. print re.findall(r'p[a-zA-Z0-9]{3,}',text) #{,1}
  33. #['python2', 'python3', 'perl', 'php4', 'php5']
  34. print re.findall(r'c[a-zA-Z]*',text) #{,inf}
  35. #['c', 'cript', 'c']
  36. print re.findall(r'c[^a-zA-Z]*',text) #{,inf}
  37. #['c++ ', 'c', 'c']
  38. # | or
  39. print re.findall(r'[pj][a-zA-Z]+',text) #{,inf}
  40. #['python', 'python', 'perl', 'java', 'javascript', 'php', 'php']
  41. # |重写上面的pattern
  42. print re.findall(r'p[^0-9]+|j[a-zA-Z]+',text)
  43. #['python', 'python', 'perl ruby lua java javascript php', 'php']
  44. print re.findall(r'p[^0-9 ]+|j[a-zA-Z]+',text)
  45. #['python', 'python', 'perl', 'java', 'javascript', 'php', 'php']
  46. # \w [a-zA-Z0-9_], \W
  47. # \d [0-9], \D
  48. # \s [ \t\n\r\f\v], \S
  49. print re.findall(r'p\w+',text) #['python2', 'python3', 'perl', 'pt', 'php4', 'php5']
  50. print re.findall(r'p\w+\d',text) #['python2', 'python3', 'php4', 'php5']
  51. print re.findall(r'p\w+[0-9]',text) #['python2', 'python3', 'php4', 'php5']
  52. print re.findall(r'p\w{5,9}',text) #['python2', 'python3']
  53. # \b word boundary
  54. # \B not \b
  55. # \A input start, ^
  56. # \Z input end, $
  57. print re.findall(r'\bp[^0-9]',text) #['py', 'py', 'pe', 'ph', 'ph']
  58. print re.findall(r'p[^0-9]\b',text) #['pt']
  59. # *? 0~inf non-greedy
  60. # +? 1~inf non-greedy
  61. print re.findall(r'p[a-z]*',text) #['python', 'python', 'perl', 'pt', 'php', 'php']
  62. print re.findall(r'p[a-z]*?',text) #['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p']
  63. print re.findall(r'p[a-z]+\b',text) #['perl', 'pt']
  64. print re.findall(r'p[a-z]+?\b',text) #['perl', 'pt']
  65. # () group
  66. # (?P<name>pattern)
  67. a=re.search(r'(p[a-zA-Z]+)([0-9])','python2',re.X)
  68. print a.group(1) #python
  69. print a.group(2) #2
  70. a=re.search(r'(?P<name>p[a-zA-Z]+)(?P<version>[0-9])','python2')
  71. print a.group('name') #python
  72. print a.group('version') #2
  73. print a.groupdict() #{'version': '2', 'name': 'python'}
  74. pattern = re.compile(r'(?P<name>p[a-zA-Z]+)(?P<version>[0-9])')
  75. results = pattern.search('python2')
  76. print results.groupdict() #{'version': '2', 'name': 'python'}
  77. results = pattern.search('python3')
  78. print results.groupdict() #{'version': '3', 'name': 'python'}
  79. results = pattern.search('php4')
  80. print results.groupdict() #{'version': '4', 'name': 'php'}
  81. #########################################
  82. for t in text.split(' '):
  83. results = pattern.search(t)
  84. if results:
  85. print results.groupdict()
  86. #{'version': '2', 'name': 'python'}
  87. #{'version': '3', 'name': 'python'}
  88. #{'version': '4', 'name': 'php'}
  89. #{'version': '5', 'name': 'php'}
  90. ###########################################
  91. a = re.compile(r"""\d + # 整数部分
  92. \. # 小数点
  93. \d * # 小数部分
  94. """, re.X)
  95. b = re.compile(r"\d+\.\d*")
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注