1. 基础知识
基础公式
// 除数取整、%除数取余、
字符串截取:
[1:]--获取从位置1开始后面的字符(默认首位是0)
[:-1]--删除位置为-1的字符(也就是获取从位置0带位置-1之间的字符)
[-1:]--获取位置-1的字符相当于 [-1]
[::-1]--倒序
lst2 = list('ajsgd')
lst2[5::-1] #?['d', 'g', 's', 'j', 'a'],倒序输出具体的值
列表倒序:
list.reverse()
使用空格连接列表中的词
' '.join(string)返回的就是中间是空的一段
.append()
.extend([1,2,3])#添加的是列表里面的数
.insert(1,56)
.remove(56)#去掉遍历列表见到的第一个56
lst1.pop()
lst1.index(2)
函数式编程:lambda,[],{},map,filter,zip,enumerate
(lambda x,y:x+y)(3,5)#8 一次性调用时不需要赋值
f2 = lambda pair: pair[0]*pair[3]#输入列表
f2([2,3,6,4,6])
output1 = [x**2 for x in range(10)]
worlist = ["red","blue","yellow"]
output = [len(x) for x in worlist]
lst=[x for x?in range(10)]
lst1 = list(zip(lst,worlist))#zip的运用,遍历lst和worlist,并对应,后面没有对应上的就舍弃
output = [(x,y) for x in lst for y in worlist if x<len(y)]#两个参数的筛选
sent = "show something, show me your code"
sent = sent.upper()
sent = sent.split(" ")##返回list
sentlist = list(sent)
sentset = set(sent)
senttuple = tuple(sent)
sent,sentlist,sentset,senttuple
(['SHOW', 'SOMETHING,', 'SHOW', 'ME', 'YOUR', 'CODE'],
['SHOW', 'SOMETHING,', 'SHOW', 'ME', 'YOUR', 'CODE'],
{'CODE', 'ME', 'SHOW', 'SOMETHING,', 'YOUR'},
('SHOW', 'SOMETHING,', 'SHOW', 'ME', 'YOUR', 'CODE'))
output = [x[0].upper() for x in list]#只大写第一个字母str可以用[]选取字母
['A', 'O', 'P']
dics = {k:sentlist.count(k) for k in sentlist}
#字典的推导式,之前是放在list里的,现在放在字典里,只要按照格式来写就行
dics = {k:list(senttuple).count(k) for k in senttuple}#tuple也是可以转换成list,count的
#map
output = list(map(lambda x:x.upper(),wordlist))#map遍历
print(output)#map不能直接输出,是一个函数,输入list
output = filter(lambda x:len(x)<5,wordlist)
#使用filter,过滤,和if相似操作,lambda后面表示的是条件
print(list(output))
def fun1(f,x):
y = x**2
return f(y,10)
def fun1(f,x):
y = x**2
return f(y,10)
f1 = lambda x,y:x+y
f2 = lambda x,y:x*y
fun1(f1,3)##19
output = collections.defaultdict(list)
for k,v in data:
output[k].append(v)
output:
defaultdict(list,
{'fall': [2],
'spring': [0, 4, 5],
'summer': [1, 6, 7],
'winter': [3, 8]})
output = collections.defaultdict(int)
for k,v in data:
output[k]+=v
print(output)
defaultdict(<class 'int'>, {'spring': 7, 'summer': 20, 'fall': 6, 'winter': 3})
sensons = ["winter","spring","summer","fall"]
x = enumerate(sensons,10)#可以从10开始计数
list(x)#enumerate,map,filter,zip都需要list来输出
WHAT'S YOUR NAME? LIHUA
WHAT'S YOUR TEL? 1123
WHAT'S YOUR ADD? GREEN
2. 简单案例
词频统计
s = 'aaajshjsd'
output = {k:s.count(k) for k in set(s)}#快捷获得词频统计,字符
output = collections.Counter(sent)#快捷获得词频统计,字符
print(output)
output = {k:sent.count(k) for k in set(sent)}#快捷获得词频统计
#统计字符串中字符的个数
str = 'All statistical techniques that simultaneously analyze multiple'
lstt = list(str)
lstt.count('e')
# 统计字符串中字符出现的次数,计入dictt中
strr = 'All statistical techniques that simultaneously analyze multiple measurements on individuals or objects under investigation'
lstt = list(strr)
dictt = {}
for i in set(strr):
num = lstt.count(i)
dictt[i] = num
#累加器,看一下实验即可
def fun(num):
return lambda y:num+y
f = fun(1)
f(2)
cont = f.read()#指针的移动
print(cont)
f.readline()#返回str
f.readlines()#读出所有的行,返回到list
#设置密码
pwd = ""
for i in range(8):
pwd += random.choice(s1)#字符str可以直接加一起
sent = "hello world,lukin is a chinese "
wdlst = sent.split(" ")
#1
wsfre = collections.defaultdict(int)#词频统计,词
for wd in wdlst:
wsfre[wd] += 1
print(wsfre)
#2
output = collections.Counter(wdlst)
#3
output = {k:sent.count(k) for k in set(sent.split(" "))}#快捷获得词频统计
#tuple解决fib
def fib(n):
a,b = 0,1
for i in range(n):
# print(i,a)
print(b)
a,b = b,a+b
fib(10)
3.关于类
class student:#类型定义
movie = "cartoon" #类的属性,直接可以用变量名称
def __init__(self,ids='000',nm="unkonwn",sco=98):#构造函数
self.id = ids#实例属性
self.name = nm
self.score = sco
def greet(self):#函数必须是self
print(self.id,self.name,"say hello to you!")
def __repr__(self):#输出相应的对象信息,可以直接调用该函数的
return "{0},{1} score:{2}".format(self.id,self.name,self.score)
stu1 = student("001","Tom",95)#创建一个student对象,实例 object
stu2 = student("002","sarah",98)
4.关于函数
def auth(quote, **speaker_info):
print(">", quote)
print("-"*(len(quote)+2))
print(type(speaker_info))
print(speaker_info)
for k, v in speaker_info.items():
print(k, "----", v)
auth("hello", name="mary",age=3, grade="pre",home="noland")
> hello
-------
<class 'dict'>
{'name': 'mary', 'age': 3, 'grade': 'pre', 'home': 'noland'}
name ---- mary
age ---- 3
grade ---- pre
home ---- noland
|