关于网站建设项目收取费用,网络系统设计与管理,互联网技术应用,有了网站怎么开发application最近在阅读《利用Python进行数据分析》#xff0c;对于Python基础进行了查漏补缺#xff0c;根据书中内容记录了常用的操作#xff0c;以备不时之需。
1.元组
元组#xff08;tuple#xff09;、列表#xff08;list#xff09;和字典#xff08;dict#xff09;是p…最近在阅读《利用Python进行数据分析》对于Python基础进行了查漏补缺根据书中内容记录了常用的操作以备不时之需。
1.元组
元组tuple、列表list和字典dict是python中最基础也是最重要的数据结构元组最大的特点是内部对象不可变这里的不可变是指元组内的对象创建后不可变但是元组包含的对象内容是可变的。
tup tuple([foo,[1,2],True])
# tup[2] False # 报错
tup[1].append(3) # 正确
tup
# 输出
(foo, [1, 2, 3], True)
元组通过号可以进行连接通过*号可以实现翻倍。
(4,None,foo)(6,0)(bar,)
# 输出
(4, None, foo, 6, 0, bar)
(foo,bar)*4
# 输出
(foo, bar, foo, bar, foo, bar, foo, bar)
*星号在变量中还可以代表任意长度的参数列表
values 1,2,3,4,5
a,b,*rest values
print(a)
print(b)
print(rest)
# 输出
1
2
[3, 4, 5]
count用来计算元组中某个元素出现的次数。
a (1,2,2,2,3,4,2)
a.count(2)
# 输出
4
2.列表
列表长度可变并且内部元素也可以改变。
a_list [2,3,7,None]
tup (foo,bar,baz)
b_list list(tup)
print(a_list)
print(b_list)
b_list[1] peekaboo
print(b_list)
# 输出
[2, 3, 7, None]
[foo, bar, baz]
[foo, peekaboo, baz]
append可以把元素添加到列表尾部insert可以把元素插入到列表的指定位置但是insert更占资源因为插入到指定位置后其他元素的位置需要发生变动还要拷贝。
b_list.append(dwarf)
print(b_list)
b_list.insert(1,red)
print(b_list)
# 输出
[foo, peekaboo, baz, dwarf]
[foo, red, peekaboo, baz, dwarf]
pop可以删除列表指定位置的元素remove会定位第一个符合要求的值并移除它。
b_list.append(foo)
print(b_list)
b_list.pop(5) # 删除最后一个foo
print(b_list)
b_list.append(foo)
b_list.remove(foo) # 删除遇到的第一个foo
print(b_list)
# 输出
[foo, red, peekaboo, baz, dwarf, foo]
[foo, red, peekaboo, baz, dwarf]
[red, peekaboo, baz, dwarf, foo]
in关键字用来检测一个值是否在列表中not in 表示不在。
dwarf in b_list
# True
dwarf not in b_list
# False
连接两个列表可以使用号和extend方法但是号方法更耗资源因为要连接过程中创建了新的对象并且要复制对象而使用extend方法比较高效。
[4,None,foo][7,8,(2,3)]
# 输出[4, None, foo, 7, 8, (2, 3)]
x [4,None,foo]
x.extend([7,8,(2,3)])
# 输出[4, None, foo, 7, 8, (2, 3)]
sort方法用于对列表排序还可以传递一个参数key用于指定排序值。
a [7,2,5,1,3]
a.sort()
# 输出[1, 2, 3, 5, 7]
b [saw,small,He,foxes,six]
b.sort(keylen) # 根据单词的长度来排序
# 输出[He, saw, six, small, foxes]
列表切片是一个非常常用的操作。切片起始位置start包含结束位置stop不包含元素个数为stop-start。如果省略的话默认从起始位置到结束位置。
seq [7,2,3,7,5,6,0,1]
seq[1:5]
# [2, 3, 7, 5]
print(seq[:5])
# [7, 2, 3, 6, 3]
print(seq[3:])
# [6, 3, 5, 6, 0, 1]
负索引从序列的尾部进行索引。
print(seq[-4:])
# [5, 6, 0, 1]
print(seq[-6:-2])
# [6, 3, 5, 6]
步进值step可以在第二个冒号后使用表示每隔多少个元素取一个值如果step-1可以实现列表的翻转。
seq[::2]
# [7, 3, 3, 6, 1]
seq[::-1]
# [1, 0, 6, 5, 3, 6, 3, 2, 7]
list内建函数sortedenumeratezipreversed。sorted可以根据list创建一个已排序的list。
sorted([7,1,2,6,0,3,2])
# [0, 1, 2, 2, 3, 6, 7]
enumerate枚举在深度学习训练中经常用到返回索引号以及训练样本数据。
some_list [foo,bar,baz]
mapping {}
for i,v in enumerate(some_list):# 字典的值是i字典的键是vmapping[v] i
mapping
# 输出{foo: 0, bar: 1, baz: 2}
zip将列表、元组或其他序列元素配对新建一个元组构成的列表。
seq1 [foo,bar,baz]
seq2 [one,two,three]
zipped zip(seq1,seq2)
list(zipped)
# 输出[(foo, one), (bar, two), (baz, three)]
zip的常用场景是遍历多个序列有时候会和enumerate一起使用深度学习训练中常用。
for i,(a,b) in enumerate(zip(seq1,seq2)):# 深度学习中可以认为i是序号a是样本b是标签print({0}:{1},{2}.format(i,a,b))
# 输出
0:foo,one
1:bar,two
2:baz,three
zip还可以实现拆分序列的功能。
pitchers [(Nolan,Ryan),(Roger,Clemens),(Schilling,Curt)]
first_names,last_names zip(*pitchers) # 这里*号起到解构的作用
# *pitchers 会将 pitchers 列表解构为三个独立的元组参数相当于
# zip((Nolan, Ryan), (Roger, Clemens), (Schilling, Curt))
print(first_names)
print(last_names)
# 输出
(Nolan, Roger, Schilling)
(Ryan, Clemens, Curt)
reversed函数用于将序列的元素倒序排列。
list(reversed(range(10)))
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
3.字典
empty_dict {}
d1 {a:some value,b:[1,2,3,4]}
# {a: some value, b: [1, 2, 3, 4]}
# 字典可以随时增加键值对
d1[7] an integer
print(d1)
# {a: some value, b: [1, 2, 3, 4], 7: an integer}
# 根据键可以获取值
print(d1[b])
# [1, 2, 3, 4]
# 检查是否含有一个键
b in d1
# True
some value in d1
# False
使用del或pop方法可以删除字典中的元素pop会返回删除的值并删除键。
d1[5] some value
d1[dummy] another value
d1
# 输出
{a: some value,b: [1, 2, 3, 4],7: an integer,5: some value,dummy: another value}
# 删除键为5的元素
del d1[5]
print(d1)
# 输出{a: some value, b: [1, 2, 3, 4], 7: an integer, dummy: another value}
# 删除键为dummy的元素
ret d1.pop(dummy)
print(ret) # 返回值another value
d1
# 输出{a: some value, b: [1, 2, 3, 4], 7: an integer}
keys和values是字典的键和值的迭代器。
print(list(d1.keys()))
print(list(d1.values()))
# 输出
[a, b, 7]
[some value, [1, 2, 3, 4], an integer]
update方法用于合并两个字典如果传递给update方法的字典的键和原字典的键重复原字典中该键对应的值将被覆盖。
# 原字典d1中有键b参数字典中也有键b因此会覆盖掉原字典中键b的值
d1.update({b:foo,c:12})
d1
# 输出
{a: some value, b: foo, 7: an integer, c: 12}
从序列生成字典
mapping dict(zip(range(5),reversed(range(5))))
mapping
# {0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
字典的键必须是不可变的对象通过hash函数可以检测一个对象是否可以哈希化即是否可以用作字典的键。
4.集合
集合里面不包含重复值和Java里面的Set一样。
set([2,2,2,1,3,3]) # set里面没有重复值
# 输出{1, 2, 3}
a {1,2,3,4,5}
b {3,4,5,6,7,8}
# 并集
print(a.union(b))
print(a|b)
# 输出{1, 2, 3, 4, 5, 6, 7, 8}
# 交集
print(a.intersection(b))
print(ab)
# 输出{3, 4, 5}
集合里面的元素是不可变的如果要包含列表需要先转换成元组。
my_data [1,2,3,4]
my_set {tuple(my_data)}
my_set # {(1, 2, 3, 4)}a_set {1,2,3,4,5}
{1,2,3}.issubset(a_set) # 判断是否是子集
# True
a_set.issuperset({1,2,3}) # 判断是否是超集
# True
{1,2,3}{3,2,1} # 所有值都相等才是相等但不考虑顺序
# True
5.列表推导式
列表推导式是非常重要也好用的一个特性也可以大大减少代码量。
列表推导表达式[expr for val in collection if condition]
字典推导表达式dict_comp {key-expr : value-expr for value in collection if condition}
集合推导表达式set_comp {expr for value in collection if condition}
strings [a,as,bat,car,dove,python]
# 遍历列表获取长度大于2的单词并转成大写
[x.upper() for x in strings if len(x)2]
# 输出[BAT, CAR, DOVE, PYTHON]# 获取列表中每个单词的长度
unique_length {len(x) for x in strings}
unique_length
# 输出{1, 2, 3, 4, 6}
更加简单的方法是用map函数map函数可以对列表等容器应用函数。
set(map(len,strings)) # 更简单的表达方式对strings应用len函数
# 输出{1, 2, 3, 4, 6}
# 遍历列表生成字典
loc_mapping {val:index for index,val in enumerate(strings)}
print(loc_mapping)
嵌套表达式
all_data [[John,Emily,Michael,Mary,Steven],[Maria,Juan,Javier,Natalia,Pilar]]
# 1.原始方法
names_of_interest []
for names in all_data:enough_es [name for name in names if name.count(e)2]names_of_interest.extend(enough_es)
print(names_of_interest)
# 输出[Steven]
# 2.嵌套表达式
result [name for names in all_data for name in names if name.count(e)2] # 先外层循环后内层循环
result
# 输出[Steven]
6.函数
函数和其他语言的函数最大的不同是可以返回多个值很方便。
def f():a 5b 6c 7return a,b,ca,b,c f()
a,b,c
# 输出(5, 6, 7)
函数最大的好处是封装一些重复的代码。使得程序结构清晰简洁。
import re
states [Alabama,Georgia!,Georgial,georgia,FlOrIda,south carolina##,West virginia?]def remove_punctuation(value):return re.sub([! #? ],,value)
# 去掉空格去掉特殊符号首字母大写
clean_ops [str.strip, remove_punctuation, str.title]def clean_strings(strings, ops):result []for value in strings:for function in ops:value function(value)result.append(value)return resultclean_strings(states, clean_ops)
# 输出
[Alabama,Georgia,Georgial,Georgia,Florida,Southcarolina,Westvirginia]# 以上操作也可以通过map方法实现# map函数将一个函数应用到一个序列上把去掉特殊符号的操作应用到列表上
for x in map(remove_punctuation, states):print(x)
7.lambda表达式
lambda表达式也是一个很方便且很实用的方法。
def short_function(x):return x*2
# 等价lambda表达式x是输入参数返回x*2
equiv_anon lambda x:x*2def apply_to_list(some_list, f):return [f(x) for x in some_list]ints [4,0,1,5,6]
apply_to_list(ints, lambda x:x*2)
# 输出[8, 0, 2, 10, 12]strings [foo,card,bar,aaaa,abab]
# 根据单词不同字母的个数排序
strings.sort(keylambda x:len(set(list(x))))
strings
# 输出[aaaa, foo, abab, bar, card]
8.生成器
some_dict {a:1,b:2,c:3}
dict_iterator iter(some_dict)
list(dict_iterator)
# 输出[a, b, c]
如需创建一个生成器只需要在函数中将返回的关键字改成yield。当你实际调用生成器时代码并不会立刻执行直到你请求生成器中的元素时才会执行它的代码。
def sequares(n10):print(Generating squares from 1 to {0}.format(n**2))for i in range(1, n1):yield i**2gen sequares()
for x in gen:print(x, end )
# 输出
Generating squares from 1 to 100
1 4 9 16 25 36 49 64 81 100
9.文件读写
python读写文件非常简单不过要注意文件读写后显示关闭除非用with语句。
with open(path) as f:lines [x.rstrip() for x in f]print(lines)
read()可以读取一定数量的字符并把移动句柄到最新的读取位置tell()函数可以获取当前句柄的位置seek()可以把句柄改变到文件中特定的位置。
f open(path,rb) # 二进制模式读取
f.read(10)
# 输出bSue\xc3\xb1a elf.tell()
# 输出10f open(path)
f.seek(3)
f.read(1)
# 输出e
# 关闭文件
f.close()
# 写入文件
with open(tmp.txt,w) as handle:# 把原文件中非空行写入到新文件中handle.writelines(x for x in open(path) if len(x)1)
Python基本操作记录了这些可以经常翻出来看看加深印象如果做好Python数据分析机器学习深度学习的话这些基础以及numpypandasmatplotlibsklearnpytorchtensorflowkeras这些相关的操作都要非常熟悉。 文章转载自: http://www.morning.xtqld.cn.gov.cn.xtqld.cn http://www.morning.fpzpb.cn.gov.cn.fpzpb.cn http://www.morning.fbnsx.cn.gov.cn.fbnsx.cn http://www.morning.mkfr.cn.gov.cn.mkfr.cn http://www.morning.mdtfh.cn.gov.cn.mdtfh.cn http://www.morning.w58hje.cn.gov.cn.w58hje.cn http://www.morning.nyqxy.cn.gov.cn.nyqxy.cn http://www.morning.qfdmh.cn.gov.cn.qfdmh.cn http://www.morning.lsxabc.com.gov.cn.lsxabc.com http://www.morning.jpydf.cn.gov.cn.jpydf.cn http://www.morning.dmxzd.cn.gov.cn.dmxzd.cn http://www.morning.rnyhx.cn.gov.cn.rnyhx.cn http://www.morning.kdnrc.cn.gov.cn.kdnrc.cn http://www.morning.qbksx.cn.gov.cn.qbksx.cn http://www.morning.qxlgt.cn.gov.cn.qxlgt.cn http://www.morning.jqswf.cn.gov.cn.jqswf.cn http://www.morning.nsppc.cn.gov.cn.nsppc.cn http://www.morning.bwmm.cn.gov.cn.bwmm.cn http://www.morning.tfqfm.cn.gov.cn.tfqfm.cn http://www.morning.yqndr.cn.gov.cn.yqndr.cn http://www.morning.wrtxk.cn.gov.cn.wrtxk.cn http://www.morning.whnps.cn.gov.cn.whnps.cn http://www.morning.ptlwt.cn.gov.cn.ptlwt.cn http://www.morning.ykkrg.cn.gov.cn.ykkrg.cn http://www.morning.npfkw.cn.gov.cn.npfkw.cn http://www.morning.qqfcf.cn.gov.cn.qqfcf.cn http://www.morning.skqfx.cn.gov.cn.skqfx.cn http://www.morning.rdxp.cn.gov.cn.rdxp.cn http://www.morning.skdhm.cn.gov.cn.skdhm.cn http://www.morning.mttck.cn.gov.cn.mttck.cn http://www.morning.rhsg.cn.gov.cn.rhsg.cn http://www.morning.hlshn.cn.gov.cn.hlshn.cn http://www.morning.mcndn.cn.gov.cn.mcndn.cn http://www.morning.rdpps.cn.gov.cn.rdpps.cn http://www.morning.rycbz.cn.gov.cn.rycbz.cn http://www.morning.tkxyx.cn.gov.cn.tkxyx.cn http://www.morning.zrkws.cn.gov.cn.zrkws.cn http://www.morning.zxwqt.cn.gov.cn.zxwqt.cn http://www.morning.rgqnt.cn.gov.cn.rgqnt.cn http://www.morning.shawls.com.cn.gov.cn.shawls.com.cn http://www.morning.wblpn.cn.gov.cn.wblpn.cn http://www.morning.bxczt.cn.gov.cn.bxczt.cn http://www.morning.rszwc.cn.gov.cn.rszwc.cn http://www.morning.hmbxd.cn.gov.cn.hmbxd.cn http://www.morning.stfdh.cn.gov.cn.stfdh.cn http://www.morning.bfysg.cn.gov.cn.bfysg.cn http://www.morning.ltkms.cn.gov.cn.ltkms.cn http://www.morning.errnull.com.gov.cn.errnull.com http://www.morning.zdwjg.cn.gov.cn.zdwjg.cn http://www.morning.rlzxr.cn.gov.cn.rlzxr.cn http://www.morning.rwrn.cn.gov.cn.rwrn.cn http://www.morning.nqlkb.cn.gov.cn.nqlkb.cn http://www.morning.rxhn.cn.gov.cn.rxhn.cn http://www.morning.fplqh.cn.gov.cn.fplqh.cn http://www.morning.rongxiaoman.com.gov.cn.rongxiaoman.com http://www.morning.ywzqk.cn.gov.cn.ywzqk.cn http://www.morning.dbrdg.cn.gov.cn.dbrdg.cn http://www.morning.qpqcq.cn.gov.cn.qpqcq.cn http://www.morning.hcwlq.cn.gov.cn.hcwlq.cn http://www.morning.fksxs.cn.gov.cn.fksxs.cn http://www.morning.guofenmai.cn.gov.cn.guofenmai.cn http://www.morning.mhpmw.cn.gov.cn.mhpmw.cn http://www.morning.gsjzs.cn.gov.cn.gsjzs.cn http://www.morning.wbxr.cn.gov.cn.wbxr.cn http://www.morning.fkyqt.cn.gov.cn.fkyqt.cn http://www.morning.mrkbz.cn.gov.cn.mrkbz.cn http://www.morning.qkgwz.cn.gov.cn.qkgwz.cn http://www.morning.ffcsr.cn.gov.cn.ffcsr.cn http://www.morning.jgykx.cn.gov.cn.jgykx.cn http://www.morning.lltdf.cn.gov.cn.lltdf.cn http://www.morning.nqypf.cn.gov.cn.nqypf.cn http://www.morning.nmnhs.cn.gov.cn.nmnhs.cn http://www.morning.jwfqq.cn.gov.cn.jwfqq.cn http://www.morning.gfhng.cn.gov.cn.gfhng.cn http://www.morning.pshtf.cn.gov.cn.pshtf.cn http://www.morning.fqmbt.cn.gov.cn.fqmbt.cn http://www.morning.mslhq.cn.gov.cn.mslhq.cn http://www.morning.bpmnq.cn.gov.cn.bpmnq.cn http://www.morning.ykyfq.cn.gov.cn.ykyfq.cn http://www.morning.ljsxg.cn.gov.cn.ljsxg.cn