python 基础教程之9 List comprehension 列表推导式, String Formatting 格式化,Useful Functions 常用的str函数

linux python基础教程 python 3.5

Posted by ivo on March 20, 2018

0x1A List comprehension 列表推导式

  • 列表推导式,是一种快速的根据规则来创建列表的方式
    >>> cubes = [i**3 for i in range(5)]
    >>> print(cubes)
    [0, 1, 8, 27, 64]
    
  • 列表推导式,里面可以包含if语句
    >>> evens=[i**2 for i in range(10) if i**2 % 2 == 0]
    >>> print(evens)
    [0, 4, 16, 36, 64]
    Create a list of multiples of 3 from 0 to 20.
    a = [i for i in range(20) if i%3 ==0]
    
  • 列表推导式如果用于创造一个巨大的range会导致MemoryError,这也并非无解后面会提到
    even = [2*i for i in range(10**100)]
    
    创建一个range 5-9 x10的list
    a = [x*10 for x in range(5,9)]
    

0x1B String Formatting 格式化

前面已经将非格式化的字符串,格式化成了字符串。在python里面还提供了一种更强大的方法把非string0的对象嵌入到str中。

  • 每个参数的格式函数放在字符串在相应的位置,这是决定使用花括号{ }。
    >>> nums = [4, 5, 6]
    >>> msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
    >>> print(msg)
    Numbers: 4 5 6
    
  • 格式化字符串可以用名称作为参数
    >>> a = "{x}, {y}".format(x=5, y=12)
    >>> print(a)
    5, 12
    >>> str="{c}, {b}, {a}".format(a=5, b=9, c=7)
    >>> print(str)
    7, 9, 5
    

0x1C Useful Functions 常用的str函数

  • 在日常的任务中,python有很多内置的函数与方法
    join(sub) - 以字符串为分隔符,插入到sub中私有的字符之间
    replace(old,new) - 旧的字符串替换成新的
    startswith and endswith - 确定字符串的开始,结束是否正确
    lower and upper 大小写
    分割方法相反的加入,将某个分隔符字符串转化为一个列表。 
    
    print(", ".join(["spam", "eggs", "ham"]))
    #prints "spam, eggs, ham"
    print("Hello ME".replace("ME", "world"))
    print("This is a sentence.".startswith("This"))
    # prints "True"
    print("This is a sentence.".endswith("sentence."))
    # prints "True"
    print("This is a sentence.".upper())
    # prints "THIS IS A SENTENCE."
    print("AN ALL CAPS SENTENCE".lower())
    #prints "an all caps sentence"
    print("spam, eggs, ham".split(", "))
    #prints "['spam', 'eggs', 'ham']"
    
  • 数值函数
    max min - 最大值,最小值
    abs - 绝对值
    round - 取整数 3.5 的3, 4.1的4
    sum - 求和
    
    >>> print(round(5.14159265))
    5
    >>> print(min(1, 2, 3, 4, 0, 2, 1))
    0
    >>> print(max([1, 4, 9, 2, 5, 6, 8]))
    9
    >>> print(abs(-99))
    99
    >>> print(abs(42))
    42
    >>> print(sum([1, 2, 3, 4, 5]))
    15
    
  • list可以作为参数来使用。返回是True。enumerate函数是枚举,遍历值的同时加标签
    >>> nums = [55, 44, 33, 22, 11]
    >>> 
    >>> if all([i > 5 for i in nums]):
    ...    print("All larger than 5")
    ... 
    All larger than 5
    >>> if any([i % 2 == 0 for i in nums]):
    ...    print("At least one is even")
    ... 
    At least one is even
    >>> for v in enumerate(nums):
    ...    print(v)
    ... 
    (0, 55)
    (1, 44)
    (2, 33)
    (3, 22)
    (4, 11)
    
    >>> nums = [-1, 2, -3, 4, -5]
    >>> if all([abs(i) < 3 for i in nums]):
    ...   print(1)
    ... else:
    ...   print(2)
    ... 
    2
    
  • Text Analyzer 文本分析
    这是一个例子项目,显示程序,分析样本文件来查找文本每个字符占用的百分比。
    test
    Ornhgvshy vf orggre guna htyl.
    Rkcyvpvg vf orggre guna vzcyvpvg.
    Fvzcyr vf orggre guna pbzcyvpngrq.
    Syng vf orggre guna arfgrq.
    Fcenfr fv orggre guna qrafr.
    Ernqnovyvgl pbhagf.
    Fcrpvny pnfrf nera'g fcrpvny rabthu gb oernx gur ehyrf.
    Nygubhtu cenpgvpnyvgl orgnf chevgl.
    Reebef fubhyq arire cnff fvyragyl.
    Hayrff rkcyvpvgyl fvyraprq.
    Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba bg thrff.
    Gurer fubhyq or bar-- naq cersrenoylbayl bar --boivbhf jnl gb qb vg.
    Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
    Abj vf orggre guna arrire.
    Nygubhtu arire vf bsgra orggre guna *evtug* abj.
    Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
    Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
    Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!
    
    >>> def count_char(text,char):
    ...     count = 0
    ...     for c in text:
    ...             if c == char:
    ...                     count += 1
    ...     return count
    ... 
    >>> filename = input("Enter a filename:")
    Enter a filename:/home/ivo/test
    >>> with open(filename) as f:
    ...     text = f.read()
    ... 
    >>> print(count_char(text,"r"))
    83
    
    def count_char(text, char):
      count = 0
      for c in text:
          if c == char:
              count += 1
      return count
    file = open("newfile.txt", "w")
    file.write("""Ornhgvshy vf orggre guna htyl.
    Rkcyvpvg vf orggre guna vzcyvpvg.
    Fvzcyr vf orggre guna pbzcyvpngrq.
    Syng vf orggre guna arfgrq.
    Fcenfr fv orggre guna qrafr.
    Ernqnovyvgl pbhagf.
    Fcrpvny pnfrf nera'g fcrpvny rabthu gb oernx gur ehyrf.
    Nygubhtu cenpgvpnyvgl orgnf chevgl.
    Reebef fubhyq arire cnff fvyragyl.
    Hayrff rkcyvpvgyl fvyraprq.
    Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba bg thrff.
    Gurer fubhyq or bar-- naq cersrenoylbayl bar --boivbhf jnl gb qb vg.
    Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
    Abj vf orggre guna arrire.
    Nygubhtu arire vf bsgra orggre guna *evtug* abj.
    Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
    Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
    Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""")
    file.close()
    filename = "newfile.txt"
    with open(filename) as f:
      text = f.read()
    for char in "abcdefghijklmnopqrstuvwxyz":
      perc = 100 * count_char(text, char) / len(text)
      print("{0} - {1}%".format(char, round(perc, 2)))
    #perc 是得到小数点
    #round 取小数点2位
    #format char round 对应0 - 1
    
    >>> nums = (55, 44, 33, 22)
    >>> print(max(min(nums[:2]), abs(-42)))
    44
    >>> print(nums[:2])
    (55, 44)