python语法笔记1--序列

1.注释:

#单行注释

ctrl + / 多行注释

2.对csv文件进行读取

方法1:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pywt
import csv
from pandas import DataFrame
df = pd.DataFrame(pd.read_csv(r'C:\Users\jiaodanyang\Desktop\PHM\data\diabetes.csv'))
data = []
data = df.loc[:,'preg']  #iloc是根据所在列的位置进行索引,loc是根据列名进行索引
print(data)

方法2:

path = r'C:\Users\jiaodanyang\Desktop\PHM\data\diabetes.csv'

data_input = []
csvFile = open(path,'r', newline='') # 设置newline,否则两行之间会空一行
reader= csv.reader(csvFile)
for item in reader:
    data_input.append(item)

print(data_input)

方法3:

with open(path,'r') as f:
    #1.创建阅读器对象
    reader = csv.reader(f)
    #2.读取文件第一行数据
    head_row=next(reader)
    print(head_row)

data_attribute = []
for item in head_row:
    data_attribute.append(item)

print(data_attribute)

以下是小甲鱼视频学习笔记:

 

1.基础知识

使用IDLE python shell工具。

1.1 查看python内置函数

>>> dir(__builtins__)

输出:['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

其中,纯小写的是python的内置函数。

查看某个具体的内置函数:

>>> help(input)

输出:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

1.2 变量

  • 在使用变量之前,要对变量进行赋值;
  • 区分大小写;
  • 变量名可以包括字母、数字和下划线。但不能以数字开头;

1.3 数据类型

  • e计数法:e+数字 表示10的几次方 如 1.5e4 = 1.5*10的4次方
  • 布尔类型: true表示1 false表示0

数据类型转换:

  • 转换为整型 int()  如果是浮点型转换为整型,则小数点后的数字被砍掉,如int(5.99)= 5
  • 转换为浮点型 float()
  • 转换为字符串 str()

判断数据类型:

  • type
  • isinstance(a,b) 其中a是变量名或者变量,b是数据类型,如果相同返回true
>>> a = 5
>>> type(a)
<class 'int'>
>>> b = 'pig'
>>> type(b)
<class 'str'>
>>> c = 1e5
>>> type(c)
<class 'float'>
>>> isinstance(a,int)
True

1.4 运算符

  • 算术运算符
>>> 10 // 8
1
>>> 10/8
1.25
>>> 5.0 // 2
2.0
>>> 11 % 3    取余
2
>>> 2 ** 3    幂次方
8 
>>> -3 ** 2
-9
>>> 3 ** -2
0.1111111111111111    幂运算操作符,比其左侧的一元运算操作符优先级高,比其右侧的一元运算操作符优先级低。

 

  • 逻辑运算符

not 取反操作符

>>> not False
True
>>> not 1
False
>>> 3<4<5    == (3<4) and (4<5)
True

1.5 分支和循环

  • elif == else if
  • 条件表达式(三元操作符)

x, y = 4, 5

if x < y:

    small = x

else:

    small = y
等价于
small = x if x < y else y
  • asset捕获异常
>>> assert 1==2
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    assert 1==2
AssertionError
  • for循环
>>> a = 'ddvvdfv'
>>> for i in a:
	print(i,end='!')

	
d!d!v!v!d!f!v!
>>> b = ['aadvdf','dfdf','fdd','dgdg','greg']
>>> for each in b:
	print(each,len(each))

	
aadvdf 6
dfdf 4
fdd 3
dgdg 4
greg 4
  • range(start,stop,step) 生成从start到stop-1的数字序列,默认步幅是1,start为空时默认是0。
>>> list(range(0,6))
[0, 1, 2, 3, 4, 5]
>>> for i in range(1,10,3):
	print(i)

	
1
4
7
>>> 

1.6 list列表

列表中可添加不同类型的元素,甚至可以向列表中添加列表。

>>> mix = ['adf',1,4.55,[1,'a',4.55]]
>>> print(mix)
['adf', 1, 4.55, [1, 'a', 4.55]]

>>> empty = []   空列表
>>> print(empty)
[]


向已建列表中添加新元素append,每次只能添加一个新元素
>>> mix.append('fgdfg')
>>> print(len(mix))
5

extend可一次性添加多个元素,但新添加的元素必须以list形式表示
>>> mix.append(['a','d'])
>>> print(mix)
['adf', 1, 4.55, [1, 'a', 4.55], 'fgdfg', ['a', 'd']]
>>> mix.extend([1,2,3])
>>> print(mix)
['adf', 1, 4.55, [1, 'a', 4.55], 'fgdfg', ['a', 'd'], 1, 2, 3]

##append可添加list,添加之后仍是list。extend添加的list是原list中的一个个元素。


insert可以向指定位置添加元素

>>> mix.insert(3,'dgfdgfdgf')
>>> print(mix)
['adf', 1, 4.55, 'dgfdgfdgf', [1, 'a', 4.55], 'fgdfg', ['a', 'd'], 1, 2, 3]

删除list中已存在的元素

remove 列表名.remove(列表元素)
>>> list = ['fdsf',1,2,3,4,5]
>>> list.remove(5)
>>> print(list)
['fdsf', 1, 2, 3, 4]

del 
del 列表名[要删除的元素下标]   
del 列表名 删除整个表
>>> del list[0]
>>> list
[1, 2, 3, 4]

pop
列表名.pop() 默认删除该列表的最后一个元素,并将该元素赋予一个变量空间
列表名.pop(要删除的元素下标)
>>> list
[1, 2, 3, 4]
>>> list.pop()
4
>>> list
[1, 2, 3]
>>> a = list.pop()
>>> a
3
>>> list
[1, 2]
>>> list.pop(0)
1
>>> list
[2]

列表切片,一次性获取列表的多个元素
列表名[start元素下标:stop元素下标] 可获取从start到stop-1的元素 长度为stop-start
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[2:5]
[3, 4, 5]
列表名[:]可实现列表复制
>>> list2 = list[:]
>>> list2
[1, 2, 3, 4, 5, 6, 7, 8, 9]

1.7 List操作符

>>> list1 = [123]
>>> list2 = [234]
>>> list1 > list2
False
>>> list1 = [123,456]
>>> list2 = [234,123]
>>> list1 > list2
False

当列表中含有多个元素时,< 和 > 比较的是列表首个元素。 
>>> list3 = [123,456]
>>> (list1 < list2 ) and (list1 == list3)
True


使用“+”进行拼接时,“+”两边必须是同种类型的数据。比如都是列表或者都是字符串。不能实现列表和字符串的拼接。
>>> list4 = list1 + list2
>>> list4
[123, 456, 234, 123]

使用“*”可以实现列表元素的复制。
>>> list3 * 3
[123, 456, 123, 456, 123, 456]
>>> list3 *= 5
>>> list3
[123, 456, 123, 456, 123, 456, 123, 456, 123, 456]

in 和 not in 只能实现同层次元素的判断。对列表中的列表的元素不能进行判断。
>>> 123 not in list3
False
>>> list5 = [123,['a','b','c'],456]
>>> 'a' in list5
False
>>> 'a' in list5[1]
True
>>> list5[1][1]
'b'

1.8 list参数

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

count查看list中某个元素出现的次数
>>> list3
[123, 456, 123, 456, 123, 456, 123, 456, 123, 456]
>>> list3.count(123)
5

index返回list中某个元素第一次出现的位置
>>> list3.index(123)
0
index(元素,start,stop)返回该元素在start到stop-1下标的范围内出现的位置
>>> list3.index(123,1,2)
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    list3.index(123,1,2)
ValueError: 123 is not in list
>>> list3.index(123,1,3)
2

reverse实现list元素逆序排列,sort实现list元素从小到大排列。
>>> list3.reverse()
>>> list3
[456, 123, 456, 123, 456, 123, 456, 123, 456, 123]
>>> list6 = [34,56,1,5,778,80,26]
>>> list6.sort()
>>> list6
[1, 5, 26, 34, 56, 80, 778]

sort默认reverse参数为false,设置为true后实现list元素从大到小排列。
>>> list6.sort(reverse=True)
>>> list6
[778, 80, 56, 34, 26, 5, 1]
  • 实现list复制时,使用分片法。

1.9 元组

  • 列表中的元素可以修改。元组中的元素不能修改。
  • list用“ [ ] ” , tuple用“ ( )”
tuple1 = (1,2,3,4,5,6,7,8)
>>> tuple1[:5]
(1, 2, 3, 4, 5)
>>> tuple1[3:]
(4, 5, 6, 7, 8)
>>> tuple2 = tuple1[:]
>>> tuple2
(1, 2, 3, 4, 5, 6, 7, 8)

#元组中的元素不能修改
>>> tuple1[1]=5
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    tuple1[1]=5
TypeError: 'tuple' object does not support item assignment
>>> temp = (1)
>>> type(temp)
<class 'int'>
>>> temp2 = ()
>>> type(temp2)
<class 'tuple'>
>>> temp3 = 1,2,3
>>> type(temp3)
<class 'tuple'>
>>> temp4 = 1,
>>> type(temp4)
<class 'tuple'>

#创建tuple元组,必须有","

>>> 3 * (5,)
(5, 5, 5)
  • 元组的更新和删除
>>> temp = (1,2,3,4)
>>> temp = temp[:2] + ('fgg',) + temp[2:]
>>> temp
(1, 2, 'fgg', 3, 4)

del 删除元组
>>> del temp
>>> temp
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    temp
NameError: name 'temp' is not defined

1.10 字符串

  • 字符串常用方法:
capitalize 将字符串小写字母改成大写,其他字母变成小写,并返回新的字符串

>>> str1 = 'xiaoxie'
>>> str1.capitalize()
'Xiaoxie'

casefold 将字符串中大写字母变成小写,并返回新的字符串
>>> str2 = 'DAXIE'
>>> str2.casefold()
'daxie'

center(width) 字符串居中
>>> str2.center(20)
'       DAXIE        '

count(sub,start,end) 返回sub在字符串中出现的次数,起始和结束位置可选
str2 = 'sfdffsa'
>>> str2.count('f')
3

endswith(sub,start,end) 判断字符串是否以sub结尾。是返回true,不是返回false
>>> str2.endswith('sa')
True

expandtabs 将字符串中\t转化为空格,默认tabsize=8
>>> str3='you\tare\ta\tdoggg'
>>> str3.expandtabs()
'you     are     a       doggg'

find(sub,start,end) 返回sub在字符串中的位置,start和end可选。
>>> str2.find('sa')
5

str.join(sub) 以str作为分隔符,插入到sub中间
>>> str5=','
>>> str5.join('123456')
'1,2,3,4,5,6'

lstrip 去除字符串左边空格
>>> str6 = '      dogggg'
>>> str6.lstrip()
'dogggg'

rstrip 去除字符串末尾空格
>>> str6='doggg    '
>>> str6.rstrip()
'doggg'

partition(sub) 以sub将字符串隔开,分为三段
>>> str6.partition('og')
('d', 'og', 'gg    ')

replace(old,new) 将old替换成new
>>> str7 = ' you are a pig'
>>> str7.replace('pig','PIG')
' you are a PIG'

split() 按照指定字符串进行切片,默认为空格,返回新的list
>>> str7='you are my fav'
>>> str7.split()
['you', 'are', 'my', 'fav']

strip 去除字符串左右两端空格
>>> str8 = '    dsff    '
>>> str8.strip()
'dsff'

swapcase 翻转字符串中的大小写


translate和maketrans(old,new) 将old全部替换成new
>>> str9 = 'aaaaaaaccccccaaaaaa'
>>> str9.translate(str9.maketrans('a','b'))
'bbbbbbbccccccbbbbbb'


  • 字符串格式化
format 格式化
>>> "{0} are {1} {2}".format("you","a","dog")
'you are a dog'

>>> "{a} are {b} {c}".format(a="you",b="a",c="dog")
'you are a dog'

>>> "{0:.1f}{1}".format(15.679,'GB')
'15.7GB'


%c 格式化字符及其 ASCII 码
>>> '%c %c %c' % (97,98,99)
'a b c'

%s 格式化字符串

%d 格式化整数

>>> '%d + %d = %d' % (1,2,1+2)
'1 + 2 = 3'

%f 格式化浮点数 
m.n m是小数点左边表示整个数一共占多少位 n 是小数点右边表示精确的位数
- 左对齐
0 空缺用0补位
>>> '%5.1f' % 27.658
' 27.7'

1.11 序列

列表、元组和字符串的共同点:

都可以通过索引得到每一个元素,默认索引值从0开始。

list() 生成list
>>> a  = list()  没带参数 生成空列表
>>> a
[]
>>> b = 'dogggg'
>>> b = list(b)
>>> b
['d', 'o', 'g', 'g', 'g', 'g']
>>> c = (1,2,3,4,5,6)
>>> c = list(c)
>>> c
[1, 2, 3, 4, 5, 6]


tuple() 生成元组

len 返回序列元素的长度
>>> len(b)
6
>>> len(a)
0

max(obj) 返回参数中的最大值
>>> max(1,2,3,4,5,5,5)
5
>>> max(b)
'o'

min(obj) 返回参数中的最小值
>>> chars='0324234'
>>> min(chars)
'0'
>>> tuple1=(0,1,2,3,4)
>>> min(tuple1)
0

enumerate
>>> list(enumerate(c))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]

zip 将不同list中下标相同的元素合并
>>> a = [1,2,3,4,5,6,7]
	 
>>> b = [5,4,3,2,1]
	 
>>> list(zip(a,b))
	 
[(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值