zoukankan      html  css  js  c++  java
  • CS_Python_Basic

      Python

      pip

      pip list 查看安装了哪些包

      pip show 查看这个包相关

      Python函数和语法

      Typora 生成目录只需要在顶端输入[TOC]别的什么都不用输入

      excel

      command + D 向下复制

      分列

      获取数据类型

      type()

      Class(object):中object的作用

      # -.- coding:utf-8 -.-

      # __author__ = 'zhengtong'

      class Person:

      """

      不带object

      """

      name = "zhengtong"

      class Animal(object):

      """

      带有object

      """

      name = "chonghong"

      if __name__ == "__main__":

      x = Person()

      print "Person", dir(x)

      y = Animal()

      print "Animal", dir(y)

      输出

      Person ['__doc__', '__module__', 'name']

      Animal ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',

      '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',

      '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

      Person类很明显能够看出区别,不继承object对象,只拥有了__doc__ , module 和 自己定义的name变量, 也就是说这个类的命名空间只有三个对象可以操作.

      Animal类继承了object对象,拥有了好多可操作对象,这些都是类中的高级特性。

      if name == ‘main’: 的作用

      __name__是系统内置变量,代表所在模块名字,也即所在文件名。

      ### demo_list.py

      b=[]

      b.append("test")

      b.append("apple")

      b.append("banana")

      for a in b:

      print(a)

      def fact(n):

      if n == 1:

      return n

      else:

      return n * fact(n-1)

      print("阶乘:", fact(3))

      print('__name__是模块名字(文件名),值为:'+__name__)

      ### function_test.py

      from demo_list import fact

      if __name__=='__main__':

      print('当前执行文件名:' + __name__)

      print("阶乘:", fact(3))

      当模块直接运行时,demo_list.py文件被直接运行,__name__的值为__main__;

      当模块被导入到其他文件,如demo_list被导入到function_test.py中,并且程序在function_test.py被执行时, demo_list.py中的__name__的值为demo_list,为其模块名,而不是__main__。而function_test.py的__name__的值为__main__,因为程序从function_test.py开始执行。

      被作为模块导入的文件当中的if __name__=='__main__':里面的代码不会执行

      zip()

      函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

      如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 ***** 号操作符,可以将元组解压为列表。

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

      >>> b = [4,5,6]

      >>> c = [4,5,6,7,8]

      >>> zipped = zip(a,b) # 返回一个对象

      >>> zipped

      # 这个对象可以直接被迭代

      >>> for i in zipped:

      print(i)

      >>> list(zipped) # list() 转换为列表

      [(1, 4), (2, 5), (3, 6)]

      >>> list(zip(a,c)) # 元素个数与最短的列表一致

      [(1, 4), (2, 5), (3, 6)]

      >>> a1, a2 = zip(*zip(a,b)) # 与 zip 相反,zip(* ) 可理解为解压,返回二维矩阵式

      # 在zip(* )这个里面写东西会被解压,就是(* )里面

      >>> list(a1)

      [1, 2, 3]

      >>> list(a2)

      [4, 5, 6]

      >>>

      enumerate() 方法

      enumerate的中文意思是枚举

      >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']

      >>> list(enumerate(seasons))

      [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

      >>> list(enumerate(seasons, start=1)) # 下标从 1 开始

      [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

      () is 元组

      argmax() 是使得 f(x)取得最大值所对应的变量点x(或x的集合)。arg即argument,此处意为“自变量”。

      with语法

      ​ 有一些任务,可能事先需要设置,事后做清理工作。对于这种场景,Python的with语句提供了一种非常方便的处理方式。

      with 语句实质是上下文管理。

      1、上下文管理协议。包含方法__enter__() 和 __exit__(),支持该协议对象要实现这两个方法。

      2、上下文管理器,定义执行with语句时要建立的运行时上下文,负责执行with语句块上下文中的进入与退出操作。

      3、进入上下文的时候执行__enter__方法,如果设置as var语句,var变量接受__enter__()方法返回值。

      4、如果运行时发生了异常,就退出上下文管理器。调用管理器__exit__方法。

      自定义类必须包含上述几个方法才能正确使用with关键字。

      contex :上下文

      class Mycontex(object):

      def __init__(self,name):

      self.name=name

      def __enter__(self):

      print("进入enter")

      return self

      def do_self(self):

      print(self.name)

      def __exit__(self,exc_type,exc_value,traceback):

      print("退出exit")

      print(exc_type,exc_value)

      if __name__ == '__main__':

      with Mycontex('test') as mc:

      mc.do_self()

      Convolutional Neural Networks, CNN 卷积神经网络

      self的含义

      class A():

      def song(one):

      print(one)

      def sing(self,one):

      print(one)

      a=A()

      A.sing(a,"hello") #注意这条语句

      a.sing("hello")

      self差不多就是java里的this

      类方法里面第一个参数必须是self

      切片

      切片操作基本表达式:object[start_index:end_index:step]

      端点是关于对象,起点终点是关于切片

      step:正负数均可,其绝对值大小决定了切取数据时的‘‘步长”,而正负号决定了“切取方向”,正表示“从左往右”取值,负表示“从右往左”取值。当step省略时,默认为1,即从左往右以步长1取值。“切取方向非常重要!”“切取方向非常重要!”“切取方向非常重要!”,重要的事情说三遍!

      start_index:表示起始索引(包含该索引对应值);该参数省略时,表示从对象“端点”开始取值,至于是从“起点”还是从“终点”开始,则由step参数的正负决定,step为正从“起点”开始,为负从“终点”开始。郑州做人流医院哪家好 http://www.020gzzj.com/

      end_index:表示终止索引(不包含该索引对应值);该参数省略时,表示一直取到数据“端点”,至于是到“起点”还是到“终点”,同样由step参数的正负决定,step为正时直到“终点”,为负时直到“起点”。

      >>>a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

      切取单个元素

      >>>a[0]

      >>>0

      >>>a[-4]

      >>>6

      当索引只有一个数时,表示切取某一个元素。

      start_index和end_index全为正(+)索引的情况

      >>>a[:6]

      >>> [0, 1, 2, 3, 4, 5]

      #step=1,表示从左往右取值,而start_index省略时,表示从端点开始,因此这里的端点是“起点”,即从“起点”值0开始一直取到end_index=6(该点不包括)。

      >>>a[6:]

      >>> [6, 7, 8, 9]

      step=1,从左往右取值,从start_index=6开始,一直取到“终点”值9。

      >>>a[:6:-1]

      >>> [9, 8, 7]

      step=-1,从右往左取值,而start_index省略时,表示从端点开始,因此这里的端点是“终点”,即从“终点”值9开始一直取到end_index=6(该点不包括)。

      start_index和end_index正(+)负(-)混合索引的情况

      >>>a[1:-6]

      >>> [1, 2, 3]

      start_index=1在end_index=-6的左边,因此从左往右取值,而step=1同样决定了从左往右取值,因此结果正确

      PyCharm

      option+command+L 自动格式化代码

      File->Settings->Editor->general->EditorTabs->Mark modified(*) 提醒文件是否修改过

      command+, 打开设置

      Anaconda

      mac包默认安装路径: /Users/zhizekai/opt/anaconda3/lib/python3.7/site-packages

      Numpy

      Pandas

      Dataframedata.isna().sum() 统计每一列有没有空值

      test_dataset = dataset.drop(train_dataset.index) 删除某个行标签的数据

      test_dataset = dataset.drop(columns="Weight") 删除某一列

      train_dataset = dataset.sample(frac=0.8,random_state=0) 随机抽样,frac 取样本的80%

      pre_train_data.keys() 和 pddata.columns 效果一样 获取column label

      pddata.iloc[1:,0] 第二行到最后,第一列

      pcadata[["净利润增长率(%)_Netprfgrrt"]] 取子集 好处是能取多列

      pcadata.info() object类型就是有空格

      concat 连接 axes=0,=1

      TensorFlow

      设置GPU按需增长

      # 设置GPU按需增长

      config = tf.ConfigProto()

      config.gpu_options.allow_growth = True

      MatplotlIb

      保存图片

      import matplotlib.pyplot as plt

      """ 一些画图代码 """

      plt.savefig("filename.png")

      plt.show()

      Jupiter lab 图像显示选择和变量输出

      #在里面显示

      %matplotlib inline

      #在外面显示

      # %matplotlib auto

      # 输出一个cel中的全部变量

      from IPython.core.interactiveshell import InteractiveShell

      InteractiveShell.ast_node_interactivity = 'all'

      散点图

      # 画散点图

      def plant_fig():

      plt.style.use('ggplot') # 好看的风格主题

      # [-1,1] 消极到积极 [0,1] 客观到主观

      plt.figure(figsize=(10,10))

      # 先是x轴,然后是y轴

      plt.plot(pre_train_data["polarity"][pre_train_data["star"] == 5],

      pre_train_data["subjectivity"][pre_train_data["star"] == 5], 'bo',label=5) # bo是蓝色的O型

      plt.xlabel("polarity")

      plt.ylabel("subjectivity")

      plt.title('Sentence emotion')

      plt.legend() # 图例

      plt.show()

      plant_fig()

      # print(pre_train_data["polarity"][pre_train_data["star"] == 5])

      绘制子图

      import matplotlib.pyplot as plt

      #创建新的figure

      fig = plt.figure()

      #必须通过add_subplot()创建一个或多个绘图

      ax = fig.add_subplot(221)

      #绘制2x2两行两列共四个图,编号从1开始

      ax1 = fig.add_subplot(221)

      ax2 = fig.add_subplot(222)

      ax3 = fig.add_subplot(223)

      ax4 = fig.add_subplot(224)

      #图片的显示

      plt.show()

  • 相关阅读:
    Luogu 1080 【NOIP2012】国王游戏 (贪心,高精度)
    Luogu 1314 【NOIP2011】聪明的质检员 (二分)
    Luogu 1315 【NOIP2011】观光公交 (贪心)
    Luogu 1312 【NOIP2011】玛雅游戏 (搜索)
    Luogu 1525 【NOIP2010】关押罪犯 (贪心,并查集)
    Luogu 1514 引水入城 (搜索,动态规划)
    UVA 1394 And Then There Was One / Gym 101415A And Then There Was One / UVAlive 3882 And Then There Was One / POJ 3517 And Then There Was One / Aizu 1275 And Then There Was One (动态规划,思维题)
    Luogu 1437 [HNOI2004]敲砖块 (动态规划)
    Luogu 1941 【NOIP2014】飞扬的小鸟 (动态规划)
    HDU 1176 免费馅饼 (动态规划)
  • 原文地址:https://www.cnblogs.com/djw12333/p/12468627.html
Copyright © 2011-2022 走看看