上班族兼职做什么好,如何减少鱼尾纹,粉红四年
type() #查看类型
dir() help() len()
open() #文本文件的输入输出
range() enumerate() zip() #循环相关
iter() #循环对象
map() filter() reduce() #函数对象
abs(-2) #取绝对值
round(2.3) #取整
pow(3,2) #乘方
cmp(3.1, 3.2) #比较大小
pmod(9, 7) #返回除法的结果和余数
max([2, 4, 6, 8]) #求最大值
min([1, 2, -1, -2]) #求最小值
sum([-1, 1, 5, 7]) #求和
int(“10”) #字符转为整数
float(4) #转为浮点数
long(“17”) # 转为长整数
str(3.5) #转为字符串
complex(2, 5) #返回复数2 + 5i
ord(“A”) #A对应的ascii码
chr(65) #ascii码对应的字符
unichr(65) #数值65对应的unicode字符
bool(0) #转换为相应的真假值,0相当于False
btw:”空” 值相当于False:[],(),{},0,None,0.0
all([True, 2, “wow!”]) #是否所有元素相当于True,全为True则为True
any([0, “”, False, [], None]) #是否有元素相当于True
sorted([1, 7, 4]) #序列升序排序
reversed([1, 5, 3]) #序列降序排序
list((1, 2, 3)) #tuple转换为表list
tuple([4, 5, 4]) #list转换为tuple
dict(a=3, b=”hi”, c=[1,2,3]) #构建字典
d = dict(a=3, b=”hi”, c=[1,2,3]) #d则为字典,字典的引用方式d[“a”]的值为3
input(‘input something’) #等待用户输入
globals() #返回全局变量名,函数名
locals() #返回局部命名空间
import os os.system('cls')
实例:
import urllib2 request = urllib2.Request("https://www.baidu.com") response = urllib2.urlopen(reques) print response.read()
urlopen(url, data, timeout)
其中
- url为URL
- data为访问URL时要传送的数据
- timeout是设置超时时间
- 返回response对象
- read方法可以返回获取到的网页内容
GET方式是直接以链接形式访问,链接中包含了所有的参数
POST把提交的数据放置在HTTP包的包体中
定义一个函数放在test.py文件中,然后添加一个above_freezing函数,则可创建一个名为test的模块。如:
def to_celsius(t): return(t-32.0) * 5.0 / 9.0 def above_freezing(t): return t>0
用法:字符串.方法
如”good”.capitalize(),输出为’Good’
在python中,列表list除了正向索引,还可以逆向索引,最后一个索引从-1开始
>>>a = [0,1,2,3,4] >>>a[-1] 4空列表:
>>>a = [1,2,3,4] >>>for i in a: >>> print i 1 2 3 4
形式:list[i:j]
其中包含i处的值,不含j处的值,i可以省略(从头开始时),若从头到尾,则可写为list[:]
f = open("test.txt","r") f.read() #read()没有参数则表示读取所有数据
“r” 表示读取
“w” 表示写入
“a” 表示追加
f = open("test.txt","r") for i in test: print len(i) #将打印出每一行的字符数
f = open("test.txt","r") for i in test: print len(i.strip()) #将去除字符串收尾两端的空白符(空格、制表符、换行符等),并返回结果
and,二元运算符
or,二元运算符
not
关系运算符
> 大于
< 小于
= 大于等于
<= 小于等于
== 等于
!= 不等于
优先级
算术运算符 > 关系运算符 > 布尔运算符
>>>if condition: >>> block
>>>if condition: >>> block >>>elif condition: >>> bolck嵌套if语句
>>>range(1,5) [1,2,3,4,5] >>>range(5,8) [5,6,7,8] >>>range(3) [0,1,2]给range()函数设置步长
>>>range(1,10,2) [1,3,5,7,9]enumerate() #该函数会返回一个由“值对”组成的列表。值对的第一个元素为索引,第二个元素为索引值
>>>for i in enumerate("abc"): >>> print i (0,'a') (1,'b') (2,'c')不规则列表
>>>while condition: >>> block
>>>text = "" >>>while text != "quit": >>> text = raw_input("Please enter a chemical formula (or 'quit' to exit):") >>> if text == "quit": >>> print"...exiting program" >>> elif text == "H20": >>> print"Water" >>> elif text == "NH3": >>> print "Ammonia" >>> elif text == "CH3": >>> print "Methane" >>> else: >>> print "Unknown compound"
>>>f = open("test.txt","r") >>>for line in f: >>> line = line.strip() #去掉每行两端的空字符 >>> print line读取网络文件(爬虫)
>>>import urllib >>>url = "https://www.baidu.com" >>>page = urllib.urlopen(url) >>>for ling in page: >>> line = line.strip() #去掉每行两端的空字符 >>> print line将两列若干行的txt文件数据放到一个列表里
>>>f = open("test.txt","r") #读取文件 >>>a = [] #存放的列表a中 >>>for i in f: >>> b = i.split() #字符行转换为列表 >>> for x in range(len(b)): >>> b[x] = float(b[x]) >>> a.append(b) #将列表b添加到a中
>>>f = open("test.txt","r") >>>f.write(“computer science") #写入,会覆盖源文件内容 >>>f.close()
>>>f = open("test.txt","a") #"a"追加数据,不会覆盖 >>>f.write(“computer science") #写入,不会覆盖源文件内容 >>>f.close()
read([size]) #以字符串 形式返回文件数据,可选的size参数用于说明读取的字节数
readlines([size]) #将文件返回为行列表,可选参数size
write(str) #将字符串写入文件
close() #关闭句柄
flush() #情况内部I/O缓存区,并将数据强行写回磁盘
seek(pos) #移动到指定的文件位置(整数)
tell() #以整数形式返回当前文件位置
closed #如果文件已关闭,则为True
集合的运算
并 union
交 intersection
添加 add
移除 remove
add() #往集合中添加一个元素,如a.add(9)
clear() #移除集合中的所有元素,如 a.clear() difference() #根据一个集合中不存在于另一个结合中的元素,创建处一个新的集合,如>>>a = set([0,1,2]) >>>b = set([1,3]) >>>a.difference(b) set([0,2])intersection() #根据两个集合中共有的元素,创建出一个新的集合
>>>a = set([0,1,2]) >>>b = set([1,3]) >>>a.intersection(b) set([1])issubset() #判断一个集合的所有元素是否都包含于另一个集合
>>>a = set([0,1,2]) >>>b = set([1,3]) >>>a.issubset(b) Falseremove() #移除集合中的一个元素
>>>a = set([0,1,2]) >>>a.remove(1) set([0,2])symmetric_difference() #根据两个集合中所有不存在与对方的元素,创建出一个新的集合。即并集-交集
>>>a = set([0,1,2]) >>>b = set([1,3]) >>>a.symmetric_difference(b) set([0,2,3])union() #并集
>>>a = set([0,1,2]) >>>b = set([1,3]) >>>a.union(b) set([0,1,2,3])散列表(hash table)
散列表元素可以是:布尔值、数字、字符串、元组tuple(不可是列表list)
>>>zidian = {"1":"cat","2":"dog"} >>>del zidian["1"] #删除字典元素 >>>zidian {"2":"dog"}字典的循环
>>>zidian = {"1":"cat","2":"dog"} >>>for i in zidian: >>> print i,zidian[i] "1","cat" "2","dog"字典方法
>>>zidian = {"1":"cat","2":"dog"} >>>zidian.get("1",99) >>>zidian.get("3",99) 'cat' 99
keys() #以列表的形式返回字典的所有键。所得到的列表中国的每个条目肯定是唯一的。如 zidian.keys()
>>>zidian = {"1":"cat","2":"dog"} >>>zidian.keys() ['1','2']
items() #返回(key, value)列表,zidian.items()
>>>zidian = {"1":"cat","2":"dog"} >>>zidian.items() [('1','dog'),('2','cat')]
values() #以列表的形式返回字典的所有值。所得列表中的每个条目不一定是唯一的。zidian.values()
>>>zidian = {"1":"cat","2":"dog"} >>>zidian.values() ['dog','cat']
update() #用另一个字典的内容对当前字典进行更新。zidian.update()
>>>zidian = {"1":"cat","2":"dog"} >>>zidian2 = {"3":"tiger"} >>>zidian.update(zidian2) >>>zidian {"1":"cat","2":"dog","3":"tiger"}
>>>counts = [809,834,477,478,307] >>>low = min(counts) >>>min_index = counts.index(low) #索引方式counts.index() >>>print min_index 4算法描述
def find_two_smallest(L): '''Return a tuple of the indices of the two smallest values in list L.''' 获取列表L中的最小元素 找出这个最小元素的索引 从列表中移除该元素 找出列表L中新的最小元素的索引 return 这两个索引
def find_two_smallest(L): '''Return a tuple of the indices of the two smallest values in list L.''' smallest = min(L) min1 = L.index(smallest) L.remove(smallest) next_smallest = min(L) min2 = L.index(next_smallest) return 这两个索引
注意算法的计算效率
>>>def linear_search(v,L): >>> i = 0 >>> while i != len(L) and L[i] != v: >>> i += 1 >>> return ifor循环型线性搜索
>>>def linear_search(v,L): >>> i = 0 >>> for value in L: >>> if value == v: >>> return i >>> i += 1 >>> return len(L)哨兵搜索
>>>def linear_search(v,L): >>> L.append(v) >>> i = 0 >>> while L[i] != v: >>> i += 1 >>> L.pop() >>> return i
def binary_search(v,L): i = 0 j = len(L) - 1 while i != j + 1: m = (i+j)/2 if L[m] < v: i = m + 1 else: j = m -1 if 0 <= i < len(L) and L[i] == v: return i else: return -1
def selection_sort(L): i = 0 while i != len(L): smallest = find_min(L,i) L[i],L[smallest] = L[smallest], L[i] i += 1 def find_min(L,b): i = b + 1 while i != len(L): if L[i] < L[smallset]: i += 1 return smallest插入排序(升序)
def insertion_sort(L): i = 0 while i != len(L): insert(L,i) i += 1 def insert(L,b): #find where to insert L[b] by searching backwards from L[b] for a smaller item. i = b while i != 0 and L[i-1] <= L[b]: i = i - 1 #move L[b] to index i, shifting the following values to the right. value = L[b] del L[b] L.insert(i,value)
合并排序(merge sort)
冒泡排序(bubble sort)
快速排序(quick sort) 堆排序(heap sort)#求传入参数的最大值 def our_max(*values): '''Find the maximum of any number of values.''' if not values: return None m = values[0] for v in values[1:]: if v > m: m = v return our_max(1) 1 our_max(1,2) 2 our_max(3,1,2,5,4,-17) 5
带*号的参数并不是必须单独出现。在函数的参数列表中,星号参数之前可以定义任意数量的常规。这些常规参数会按照正常的方式与值进行配对,然后将所有值做成一个元组并赋值给星号参数。values前面的*的作用:告诉python将当次调用的所有参数做成一个元组,并将该元组赋值给values。当没有提供任何值的时候,values就会被赋值为一个空元组。
def append_all(old, *new): for n in new: old.append(n) return old values = [] append_all(values,1,2,3) [1,2,3] append_all(values) [1,2,3]
命名参数python不允许单个函数中出现两个或两个以上的星号参数,因为在将它们跟值进行配对的过程中会出现歧义。
def describe_creature(name, species, age, weight): return '%s (%s): %d years, %d kg' %(name,species,age,weight) print describe_creature(name = 'Charles', species = 'Homo', age = 28, weight = 70) #按照参数正常顺序传入 Charles(Homo): 28 years, 70 kg
def describe_creature(name, species, age, weight): return '%s (%s): %d years, %d kg' %(name,species,age,weight) print describe_creature(age = 28, species = 'Homo', name = 'Charles', weight = 70) #变换参数顺序 Charles(Homo): 28 years, 70 kg
from Tkinter import * window = Tk() #创建根窗口Tkinter小插件
from Tkinter import * window = Tk() #创建根窗口 label = Label(window, text = "this is our label.") label.pack() #pack()方法
pack()方法,其它插件也可以用,用于将该插件置入其父插件中,并告诉其父插件要根据实际情况改变其大小。如果忘记了调用该方法,则子插件要么就不显示,要么就显示不正确。
Frame 组织其它插件
from Tkinter import * window = Tk() frame = Frame(window) frame.pack() first = Label(frame, text = "first label") first.pack() second = Label(frame, text = "second label") second.pack() third = Label(frame, text = "third label") third.pack() window.mainloop()Entry 可输入单行文本
from Tkinter import * window = Tk() frame = Frame(window) frame.pack() var = StringVar() label = Label(frame, textvariable = var) label.pack() entry = Entry(frame, textvariable = var) entry.pack() window.mainloop()
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python爬虫:Request Payload和Form Data的简单区别说明
浅谈Python中threading join和setDaemon用法及区别说明
Python3-异步进程回调函数(callback())介绍
python继承threading.Thread实现有返回值的子类实例
Python中使用threading.Event协调线程的运行详解
网友评论