zoukankan      html  css  js  c++  java
  • COMP9021--6.6

    1. 在print结尾处添加end=''

    print默认在字符串结尾处添加换行符,添加end=''后表示这个语句并没有结束,结尾不换行

    2. 为了减少重复代码以及便于修改,我们可以编写函数

    1) 函数编写中出现的问题只有在调用并执行该函数时才能被发现

    2) def 函数名(形参列表, 可以不写,多个时用逗号隔开,不需要声明类型但是可以设置默认值):

      ''' 注释 '''

      pass( 不确定函数用途时用 )

    3) 函数调用时传入实参   函数名(实参)

    4) 当在函数内部对形参进行修改时,实参的值并不会被影响

    3. 换行

    4. continue end this loop and back to where it earlier in last loop

    5. 在字典中,字典的key必须unchangeable,故不能使用list,可以使用tuple。 但字典的value can be changed

    6. tuple

    1)>>> T=3,5,10

    >>> T

    (3, 5, 10)

    2) >>> T=(10)
    >>> T
    10

    若我们只有一个数但仍想保留元组结构,就保留逗号,如(10,)

    7. 文件处理(更多详见之前的文件操作)

    待处理的文件要与pl存储在一个目录中,或指定完整路径

    1)open模式打开

    f1=open('file1.txt','r')   read

    f2=open('file2.txt,'w')  write

    操作结束之后一定要关闭文件  f1.close()

    2)with open模式打开

    with open('file1.txt') as file_name:

      next(file_name) 打印下一行

      next(file_name)

    或: for line in file_name: 然后进行操作

    操作结束之后不需要关闭文件

    lines=file_name.readlines()方法读取文件所有行,并保存在一个list中,每行作为一个元素,内存量占用较大

    lines=file_name.readline()方法每次只读取文件的一行,返回一个字符串对象,占用内存较小

    lines=file_name.read([size])方法从文件当前位置起读取size个字节,若无参数size,则表示读取至该文件结束为止

    若想输出某较大文件的第几行,可以用linecache,如text = linecache.getline(‘file1.txt',2)

    8. str.startswith(str, beg=0,end=len(string)),beg与end均为可选参数,表示起始与终止位置,用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False

    9. str.isspace() 方法检测字符串是否只由空白字符组成,是则返回True。若str为空依旧返回False

    10. split方法中,若分隔符用于开头或者两个分隔符连在一起,我们得到一个''。分隔符默认值为空格

    11. 字典( to map things together )

    1)locals()表示局部变量,globals()表示全局变量

    2)zip可以创建字典

    >>>keys=['a','b','c']

    >>>values=[1,2,3]

    >>>dictionary=dict(zip(keys,values))

    3) 赋值:D{'a'}='A',things will be overwrite if you map again

    4) if we just say is it in dic, it will look at the key

    12. index
    to find the first position of what you want from left side, do not out of range

  • 相关阅读:
    LeetCode--414--第三大的数
    LeetCode--412--Fizz Buzz
    LeetCode--409--最长回文串
    《Cracking the Coding Interview》——第18章:难题——题目6
    《Cracking the Coding Interview》——第18章:难题——题目5
    《Cracking the Coding Interview》——第18章:难题——题目4
    《Cracking the Coding Interview》——第18章:难题——题目3
    《Cracking the Coding Interview》——第18章:难题——题目2
    《Cracking the Coding Interview》——第18章:难题——题目1
    《Cracking the Coding Interview》——第17章:普通题——题目14
  • 原文地址:https://www.cnblogs.com/eleni/p/10987850.html
Copyright © 2011-2022 走看看