机器学习-python基础

更新时间:2019-12-24 10:35:22 点击次数:1335次

# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 10:15:39 2019
@author: zhh
"""
import math
'''1、基本语法'''
#同行显示多行语句:用";"分号隔开
#print输出:
#print默认换行,若要 不换行在变量末尾加上逗号,end=''
x='a';y='b'
print(x,end='') #不换行
print(y) #默认换行
print(x,y) #不换行 “a b”
 
'''2、数据类型'''
'''数值'''
#round(x,d) 对浮点数x四舍五入,d是小数位保留几位
round(4.33345,4) #4.3335
round(4.33345,2)
#ceil向上取整 floor向下取整
math.ceil(4.1) #向上取整2
'''字符串'''
#输入
a=input('')
b=int(input(''))
print(type(b)) #int
#格式化输出
#% 如'''字典形式!!!'''
print('hello! I %(v1)s a %(v2)s'%{'v1':'am','v2':'student!'})
#hello! I am a student!
#format:括号{}代替%s,利用format()函数指定字符串
print('hello! I {} a {}!'.format('am','student'))
#指定位置
print('{0} {1} {0}'.format('am','student')) #am student am
#格式化输出
print("{:.2f}".format(3.1415)) #3.14
 
#字符串基本运算
#+连接
print('ab'+'cd') #abcd
#*重复输出
print("ab"*2) #abab
#切片
print("abcd"[1:-2]) #b
print("abcdefg"[0:7:2]) #aceg 索引0到6 步长为2
#替换
str1='abcdweghi'
str1.replace('we','ef') #'abcdefghi' 老的换成新的
#分割
str1='ab,cd,weg,hi'
str1.split(',') #['ab', 'cd', 'weg', 'hi']
 
'''列表'''
#通过索引访问值
#del 删除指定索引元素
list1=['a','b','c','d']
del list1[1] #['a', 'c', 'd']
#remove 删除指定值
list1=['a','b','c','d']
list1.remove('a') #['b', 'c', 'd']
#pop 删除指定索引 无参数时删除最后一个元素
list1=['a','b','c','d']
list1.pop(1) #['a', 'c', 'd']
#清空列表所有元素
list1.clear() #[]
#append 增加元素到列表末尾
list1=['a','b','c','d']
list1.append('e') #['a', 'b', 'c', 'd', 'e']
#extend 将一个列表元素全部增加到另一个列表中
list1=['a','b','c','d']
list2=['e','f','g']
list1.extend(list2) #['a', 'b', 'c', 'd', 'e', 'f', 'g']
#insert 在指定位置增加元素
list1=['a','b','c','d']
list1.insert(1,'x') #['a', 'x', 'b', 'c', 'd']
#在列表中查找元素是否存在in /not in
x='a'
list1=['a','b','c','d']
if x in list1: #如果存在则结果为True
    print("在")
else:
    print("不在")
 
#排序
#倒置
list1=['a','b','c','d']
list1.reverse() #['d', 'c', 'b', 'a']
#排序(默认从小到大)
list1=['b','a','d','c']
list1.sort() #['a', 'b', 'c', 'd']
#倒序 reverse=True
list1=['b','a','d','c']
list1.sort(reverse=True) #['d', 'c', 'b', 'a']
 
#嵌套
list1=[['a','b'],['w','f','e']] #二维列表
print(list1[1][0]) #w
# + 连接    *重复输出
list1=['a','b','c','d']
list2=['e','f']
print(list1+list2) #['a', 'b', 'c', 'd', 'e', 'f']
print(list1*2) #['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
 
'''元组'''
#不可修改
tup1=('a','b','c')
tup2=('d','e')
#访问
print(tup1[1]) #b
# +连接
print(tup1+tup2)
print(tup1*2)
#del 删除整个元组
del tup1
#print(tup1) #name 'tup1' is not defined
 
 
 
#
tup2=('d','e')
print(len(tup2))
print(max(tup2))
print(tup2[0:2])
 
#与列表相互转换
tup1=('a','b','c')
list1=list(tup1)
list2=['d','d','f']
tup2=tuple(list2)
 
'''字典'''
dict1={'name':'zhh','age':'18'}
del dict1['name']
dict1.clear() #清空字典所有元素
dict1={'name':'zhh','age':'18'}
dict1.keys()
dict1.values()
dict1.items() #dict_items([('name', 'zhh'), ('age', '18')])
 
'''集合'''
#无序不重复元素的序列
#创建
b_set=set() #空集合 不能用{}创建空集合
b_set=set(['22','d','d','v']) #{'22', 'd', 'v'}
a_set={'ff','ff','d'} #{'d', 'ff'}
 
#del只能删除集合
a_set={'a','b','c','d'}
del a_set 
#pop 删除一个随机元素
a_set={'a','b','c','d','e'}
a_set.pop()
#remove删除指定元素
a_set={'a','b','c','d','e'}
a_set.remove('a')
a_set.clear()
print(a_set)
#add增加元素
a_set={'a','b','c','d'}
a_set.add('e') #{'a', 'b', 'c', 'd', 'e'}
#一般格式为:s.update(s1,s2,...sn),其中功能是用集合s1,s2,...,sn中的成员
#修改集合s,s等于s与s1、s2...的并集。
a_set.update({3,4},{'rr','ff'}) #{3, 4, 'a', 'b', 'c', 'd', 'e', 'ff', 'rr'}
 
#可以使用"-"、"|"、"&"运算符进行集合的差集、并集、交集运算。
a=set('abcd')
b=set('cdef')
print(a)
print(a-b) #a中集合除去b里有的 {'a', 'b'}
print(a|b) #并集 {'a', 'f', 'd', 'b', 'e', 'c'}
print(a&b) #交集 {'c', 'd'}
 
'''逻辑预算符号'''
#and 与  or 或 not 非
 
'''函数'''
#在Python中,数值、字符串与元组是不可更改的类型,而列表、字典等则是可以修改的类型,函数参数采用不同方式传递。
#(1)可更改类型
#类似C++的引用传递(如列表、字典),将参数真正的传入函数;函数内部修改参数值后,函数外部被传入的参数也会受影响。
 
#例:
def changeme( mylist ): 
    mylist.append([1,2,3,4]) 
    print ("函数内取值: ", mylist) 
    return 
mylist = [10,20,30] 
changeme( mylist ) 
print ("函数外取值: ", mylist)
#结果:函数内取值: [10, 20, 30, [1, 2, 3, 4]] 
      #函数外取值: [10, 20, 30, [1, 2, 3, 4]]
      
#(2)不可变类型(如数值、字符串、元组)
#类似C++的值传递,传递的只是参数的值,不影响参数本身;函数内部修改参数值后,函数外部被传入的参数不受影响。
#实例:
def ChangeInt( a ):
     a = 10 
b = 2 
ChangeInt(b) 
print( b )
#结果:2
 
'''匿名函数!!!'''
#匿名函数不再使用def定义的函数,需要使用lambda关键字。
#声明格式:lambda [arg1 [,arg2,.....argn]]:表达式
 
sum = lambda a1,a2 : a1+a2 #只能访问自己参数列表的参数!!!
print(sum(2,3)) #5
 
'''面向对象'''
class Cat:
    print('cat')
#实例化对象
x=Cat() #cat
 
class Test:
    i='aa'
    #方法
    def test1(self):
        return 'dede'
#实例化对象            
x=Test()
#调用类的方法
print(x.test1()) #'dede'
#调用类的属性
print(x.i)
#增加类的数学
x.co='aaa'
print(x.co) #aaa
 
 
#self
class Car:
    #构造方法
    def __init__(self,color):
        self.strcolor=color
    #类的方法
    def toot(self):
        print("这是%s色的车"%self.strcolor)
car = Car('red') #自动调用构造方法,赋值
car.toot() #这是red色的车
 
#文件
f = open("foo.txt", "w")
f.write( "Python 是一个非常好的语言。/n是的,的确非常好!!/n" )
f.close()
 
#此时打开文件 foo.txt,显示如下:
#Python 是一个非常好的语言。 
#是的,的确非常好!!
 
f = open("foo.txt", "r") 
str = f.read() 
print(str) 
# 关闭打开的文件 
f.close()
 
 
#Python 是一个非常好的语言。 
#是的,的确非常好!!
 
#f.readline()会从文件中读取单独的一行。f.readline()如果返回一个空字符串, 说明已经已经读取到最后一行。
 

本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是一个个人学习交流的平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽,造成漏登,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

回到顶部
嘿,我来帮您!