Python学习笔记(usyd info1110)

About me

本蒟蒻是悉尼大学计算机科学大一的学生,这篇博客记录了学习INFO1110这门课的一些心得,希望能对大家有帮助。

To start with

因为计算机只能识别机器语言,所以我们需要编译器将其他语言翻译成机器语言。编译器有编译(complier)和解释(interpreter)两种。python是属于解释型语言。

编译型语言:程序在执行前需要一个专门的编译过程,把程序编译成机器语言的文件,运行时不需要重新翻译,直接使用编译的结果。效率高,跨平台略差
解释型语音:编写的程序不进行预先编译,以文本方式储存代码,会将代码一句一句直接运行。要先解释再运行

Python的安装网上教程很多,这里不再赘述
执行python的几种方式

  1. 解释器运行
    用记事本(e.g. sublime)写好文件,保存在本地(记得文件要以.py结尾,这能让计算机知道这是一个python文件),在终端输入:
# python3 文件名.py
python3 hello.py

你也可以编译python文件:

python -m py_compile HelloWorld.py
# This makes a .pyc file for your program. The class file is called HelloWorld.class
python HelloWorld.pyc
  1. 交互式运行:
    在终端输入python3进入Python环境,不需要输入要执行的文件名,多用于验证局部语法或代码,但不能保持和运行过大程序 。输入exit()退出环境

  2. IDE(集成开发环境):
    集成了开发开发软件需要的工具包括图形界面,代码编辑器,解释器,调试器,比较常用的是pycharm

变量

变量类型:

  • 数字型:
    int: 整数, e.g. 10
    bool: 布尔,e.g. 0,1,True, False
    float: 浮点数/小数,e.g. 0.5

  • 非数字型
    str:字符串
    list: 列表
    tuple: 元组
    dict: 字典

Python允许你同时为多个变量赋值:

 a = b = c = 1 
 print(a) //1
 print(b) //1

也可以为多个对象指定多个变量:

a, b, c = 1, 2, "Joe He"
print(a) //1
print(c) //Joe He

注释

注释里的代码不会被执行。
快捷键:sublime和vscode里,选中要注释的代码(一行的话可以 ctrl+L),ctrl+/ 一键注释

# 这是一个当行注释,不会被运行

'''
这是一个多行注释
程序员最讨厌两件事:
第一是写注释
第二是别人不写注释
'''

字符串

合并字符串

用+号把两个字符串连接起来

first_name=“Joe” 
last_name=“He” 
full_name=first_name+" "+last_name 
print(full name)
# Joe He

修改字符串大小写

str.title(): 字符串内所有的首字母母大写, 注意are’t会变成Are’T
str.capitalize(): 字符串的第一个单词的首字母大写, “there is a tree” -> “There is a tree”
str.upper(): 字符串的所有单词大写
str.lower(): 字符串的所有单词小写
name="joe he"

print(name.title())  #Joe He

print(name.capitalize()) # Joe he

print(name.upper()) # JOE HE

print(name.lower())# joe he

转义字符

Python识别字符串时,以 ’ (quote) 开头,以 ’ 结尾。 如果文字中有 ’ 或 ‘’ 会导致python无法读完全部文字。e.g. ‘I’am OK.’。这时候我们需要转义字符

# 转义
print('I\'m ok.') 
# 制表符 (tab)\t
print("\tpython") 
# 换行符 \n 
print("Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" )

删除头尾的空白

strip():用于移除字符串头尾指定的字符
rstrip(): 删除 string 字符串末尾的指定字符
lstrip():用于截掉字符串左边的空格或指定字符

string = '  hello  '
string.strip() #'hello'

favourite language = 'python  ' 
favourite language.rstrip() # 'python'
number = 'foo123'
number.rstrip('0123456789') # 'foo'

忽略新行

Python中每次print都会另起一行, 默认是print(‘xx’, end = ‘\n’),我们可以用一下方法忽略新行

print("line1 \ 
line2 \ 
line3") // line1 line2 line3

print("#", end="")

格式化

当我们想把变量以某种特殊格式输出时,我们可以用格式化

//把string看做object,调用format method
name = 'Joe'
print("hello, {}".format(name))

一些常用的格式化:

#()里可以是字符串或数字
'{} {}'.format('one', 2)    #'one 2'

#传入顺序可以通过数字1,2换
'{1} {0}'.format('one', 'two')   #'two one'

#format里套format
'{:>{}}'.format('hello', 10) #'     hello'

#打印{}
'{{{}}}'.format('hello') #{hello}

String类

#10个字符框,靠右 
'{:>10}'.format('test')  #'      test'

#靠左 
'{:10}'.format('test') #'test      '

#靠左,10位,剩余的用_补齐
'{:_<10}'.format('test')  #'test______'

#居中
'{:^10}'.format('test') #'   test   '

#只取前几个字符
'{:.5}'.format('xylophone') # xylop '
'{:10.5}'.format('xylophone') #'xylop     '

Number类

#整数
'{:d}'.format(42) #'42'

#保留小数点后六位 
'{:f}'.format(3.141592653589793) # 3.141593 

#不足4位用空格补
'{:4d}'.format(42) # '  42'

#六位,不足时0占位,保留到小数点后2位 
'{:06.2f}'.format(3.141592653589793 #003.14 

'{:+d}'.format(42) # +42
'{: d}'.format((- 23)) # -23 
'{:=+5d}'.format(23) # +     23

读写文档

Python可以读入并改写文档 (.txt等),常见的有两种方法:

file = open('filename.txt', 'r')
print(file.readline())
file.close()

or

with open('filename.txt', 'r') as file:
	print(file.readline())

这两个区别是第一种方法最后需要 file.close(), 第二种不需要。open()的第一个参数是要打开文件的名字,第二个参数是打开的模式(常用的模式有’r’和’w’)。

read模式

读文档有read(), readlines(), readline()这几种方法

// test.txt, 与py文件在同一目录下。
deposit 5.00 
withdraw 2.05 
deposit 15.30 
withdraw 935.50 
wdeposit 500.50

read()

读取全部内容,返回一整个字符串

f = f.open('test.txt', 'r')

print(f.read())
#
deposit 5.00 
withdraw 2.05 
deposit 15.30 
withdraw 935.50 
deposit 500.50

# 如果想返回一个数组:
print(f.read().split())
#
['deposit', '5.00', 'withdraw', '2.05', ..]

f.close()

readline()

读取一行,返回一个字符串
注意myfile.readline()一定要赋值给line,要不然if myfile.readline==""会跳过一行

with open('test.txt','r') as myfile: 
      while True: 
            line=myfile.readline()
            if line=="": 
                  break
            print(line,end="")
#
deposit 5.00 
withdraw 2.05 
deposit 15.30 
withdraw 935.50 
deposit 500.50

# 如果想返回数组
with open('transactions.txt','r') as myfile: 
      while True: 
      line=myfile.readline().split() 
      if line==[]: 
            break 
      print(line) 
# 
['deposit', '5.00'] 
['withdraw', '2.05'] 
['deposit', '15.30'] 
['withdraw', '935.50'] 
['deposit', '500.50']

readlines()

读取全部内容,返回一个数组。会把行末尾的\n读进去,所以要手动去除

a=myfile.readlines()
print(a)
#['deposit 5.00\n', 'withdraw 2.05\n', 'deposit 15.30\n', 'withdraw 935.50\n', 'deposit 500.50']  

lines=[] 
for line in a: 
      lines.append(line.rstrip("\n")) 
print(lines) 
#['deposit 5.00', 'withdraw 2.05', 'deposit 15.30', 'withdraw 935.50', 'deposit 500.50']

Write模式

往file里写内容,会清空之前file的内容。不想内容被清空可以用mode 'a'
f.write()的括号里只能是字符串

f = f.open('test.txt','w')
f.write('Hello')
f.close()

数组

数组是包含多个相同类型值的连续内存块。通过index来访问和修改数组中间储存的值。

# 在python中数组可以存放不同类型的值
a = [1, 'hello']
print(a[0])
# 1

a[0] = 'hi'
print(a)
# ['hi', 'hello']

#在python中,两个数组可以直接做赋值运算
b = a
print(b == a) #Ture

创建特殊数组的几个技巧:

a = [0]*4 
print(a) #[0,0,0,0]

a = list(range(5))
print(a) #[0, 1, 2, 3, 4, 5]
#range(start,stop,step)


[i for i in range(5)]
print(a) #[0, 1, 2, 3, 4, 5]

修改列表

motorcycles=['honda','yamaha','suzuki']
  1. 在末尾添加元素
motorcycles.append('ducati')
  1. 在列表插入元素:
motorcycles.insert(0,'ducati')
# 方法insert在索引0处添加空间,并将值'ducati'存储在这。
  1. 在list末尾加另一个列表的值:
list.extend(list2)
  1. 统计某个元素在列表中出现的次数:
list.count()
  1. 删除元素:
del mortorcycles[0]
  1. 删除元素并接着使用它的值:pop()删除列表末尾的元素,并能接着使用它。在括号里输入索引,删除列表中的任意元素
motorcycles=['honda','yamaha','suzuki']
last_ownd=motorcycles.pop()
print("The last motorcycle I owned was a"+last_owned.title()+".")  # suzuki储存在last_owned中
  1. 根据值删除元素:
motorcycles.remove('ducati')
  1. 连接数组形成字符串
stuff = ['Apples', 'Oranges', 'Crows' ,'Telephone']
print(' '.join(stuff))
#  Apples Oranges Crows Telephone

在list中穿插一个字符串并连接起来

print('#'.join(stuff[3:5]))
# Telephone#Light
  1. list():转化成列表, 必须是iterable才能转化,数字就不行
    转化字符串时会拆开:
test = list('cat')
test
['c', 'a', 't']
  1. 确认一个元素是否在数组内
a=[1,2,3]
print(1 in a) #true

组织列表

  1. 永久性排序-按字母顺序
cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)

sort方法只会改变调用他的数组,没有返回值

a=[3,2,1]
b=a.sort()
print(a) #[1,2,3]
print(b) #None

与字母顺序相反:向方法传递参数sort(reverse=True)
2. 临时排序

cars=['bmw','audi','toyota','subaru']
print(sorted(cars))

函数sorted会返回一个新的数组

a=[3,2,1]
b=sorted(a)
print(b) #[1,2,3]
  1. 倒着打印-永久性,想恢复再次用reverse
cars=['bmw','audi','toyota','subaru']
	cars.reverse()
	print(cars)

复制数组及枚举

在函数中传入数组时,传入的是数组的地址,所以会改变原来的数组。如果不想原来的数组被改变,我们就需要复制一个新的数组。

new_list = old_list.copy()
# or
new_list = old_list[:]
# or
new_list = list(old_list)

使用enumerate进行枚举:

notes = [50,20,10]
new_collection = enumerate(notes)
print(list(new_collection))
# ((0,50),(1,20),(3,5))

notes = [50,20,10]
for (index, v) in enumerate(notes):
print("{}{}".format(v,index))

或者使用zip:

indices =[0,1,2]
notes = [50,20,10]
new_collection = zip(indices, notes)
print(list(new_collection))
posted @ 2020-07-13 16:38  AKAjojo  阅读(351)  评论(0编辑  收藏  举报