广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python学习笔记2—python文件
  • 574
分享到

python学习笔记2—python文件

学习笔记文件python 2023-01-31 02:01:58 574人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

python学习笔记2——Python文件类型、变量、数值、字符串、元组、列表、字典一、Python文件类型1、源代码python源代码文件以.py为扩展名,由pyton程序解释,不需要编译[root@localhost day01]# v

python学习笔记2——Python文件类型、变量、数值、字符串、元组、列表、字典


一、Python文件类型

1、源代码

python源代码文件以.py为扩展名,由pyton程序解释,不需要编译

[root@localhost day01]# vim 1.py
#!/usr/bin/python       
print 'hello world!'
[root@localhost day01]# python 1.py
hello world!

2、字节代码

Python源码文件经过编译后生成的扩展名为‘pyc’的文件

编译方法:

import py_compile

py_compile.compile('hello.py')

[amos@AAC-DMP-03 amos]$ vim 2.py
#!/usr/bin/pyton
import py_compile
py_compile.compile('./1.py')
[root@localhost day01]# vim 2.py
#!/usr/bin/python
import py_compile
py_compile.compile('1.py')
[root@localhost day01]# python 2.py 
[root@localhost day01]# ls
1.py  1.pyc  2.py
[root@localhost day01]# python 1.pyc 
hello world!

3、优化代码

经过优化的源码文件,扩展名为“pyo”

-python -O -m py_compile hello.py

[root@localhost day01]# python -O -m py_compile 1.py
[root@localhost day01]# ll
total 16
-rw-r--r--. 1 root root  41 Feb 21 17:55 1.py
-rw-r--r--. 1 root root 113 Feb 21 17:56 1.pyc
-rw-r--r--. 1 root root 113 Feb 21 18:15 1.pyo
-rw-r--r--. 1 root root  67 Feb 21 17:56 2.py
[root@localhost day01]# python  1.pyo
hello world!

二、Python变量

变量是计算机内存中的一块区域,变量可以存储规定范围内的值,而且值可以改变。

python下变量是对一个数据的引用

python是指向内存的另外一块区域,而C语言是对内存的一块区域的值重新赋值

变量的命名

变量名由字母、数字、下划线组成

不能以数字开头

不可以使用关键字

-a a1 _a


变量的赋值

是变量的申明和定义的过程

a = 1

id(a) //发现从新赋值a之后,变量a在内存中的地址从7601952变化为16579968

[root@localhost day01]# ipython
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56) 
Type "copyright", "credits" or "license" for more infORMation.
IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
In [1]: a=123
In [2]: print a
123
In [3]: id(a)
Out[3]: 7601952
In [4]: id(a)
Out[4]: 7601952
In [5]: a = 456
In [6]: id(a)
Out[6]: 16579968

三、Python中的运算符与表达式

Python的运算符包括

 赋值运算符 x = 3,y = 'abcd' *=  /=  %=  x+=2 x=x+2 x-=2 x=x-2

 算数运算符 + - * / % // **

 关系运算符 > < >= <= == != 返回结果是bool值true或者false

 逻辑运算符 and逻辑与:true and false  or逻辑或false or true  not逻辑非not true


定义变量不需要申明字符类型

In [17]: x=2
In [18]: type(x)
Out[18]: int
In [19]: x='david'
In [20]: type(x)
Out[20]: str

算数运算符真是简洁明了4.00 // 3=1.0表示取整,3**2=9 表示3的平方

In [29]: 'a' +'b'
Out[29]: 'ab'
In [30]: 3-4
Out[30]: -1
In [31]: 3*2
Out[31]: 6
In [32]: 4/3
Out[32]: 1
In [33]: 4.0 /3
Out[33]: 1.3333333333333333
In [34]: 4.0 // 3
Out[34]: 1.0
In [35]: 4.00 // 3
Out[35]: 1.0
In [36]: 4%3
Out[36]: 1
In [37]: 2**3
Out[37]: 8
In [38]: 3**2
Out[38]: 9


关系运算符

In [39]: 1>2
Out[39]: False
In [40]: 1<9
Out[40]: True
In [41]: 1!=9
Out[41]: True

逻辑运算符

In [42]: 1==1 and 2>1
Out[42]: True
In [43]: 1==1 and 2<1
Out[43]: False
In [44]: 1==1 or 2<1
Out[44]: True
In [45]: not 1==2
Out[45]: True

Lambda(从上到下,优先级越来越高,同行右侧优先级更高)

逻辑运算:or

逻辑运算: and

逻辑运算:not

成员测试:in,not in

同一性测试:is,is not

比较:<,<=,>,=>,!=,==

按位或:|

按位异或:^

按位与: &

移位:<<,>>

加法与减法:+,-

乘法与除法和取余:*,/,%

正负号:+x,-x

按位翻转:~x

指数:**


例子:写一个四则运算器

要求从键盘读取数字

[root@localhost day01]# vim 3.py
#!/usr/bin/python
num1=input('Please input a number')
num2=input('Please input a number')
print "%s+%s=%s" %(num1,num2,num1+num2)
print "%s-%s=%s" %(num1,num2,num1-num2)
print "%s*%s=%s" %(num1,num2,num1*num2)
print "%s/%s=%s" %(num1,num2,num1/num2)
[root@localhost day01]# python 3.py 
Please input a number2
Please input a number3
2+3=5
2-3=-1
2*3=6
2/3=0

input()与raw_input()去别:

input() 接受数字和字符串

raw_input()全部解析为字符串

In [47]: input ("Please input: ")
Please input: 123
Out[47]: 123
In [48]: input ("Please input: ")
Please input: abc #这里报错,input输入字符串必须加'abc'引号,否则识别不了
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-48-ae0272fccd43> in <module>()
----> 1 input ("Please input: ")
<string> in <module>()
NameError: name 'abc' is not defined
In [49]: input ("Please input: ")
Please input: 'abc'
Out[49]: 'abc'
In [50]: input ("Please input: ")
Please input: 6789
Out[50]: 6789
In [51]: raw_input ("Please input: ")
Please input: sdfsahfha
Out[51]: 'sdfsahfha'
In [52]: 234
Out[52]: 234
In [53]: raw_input ("Please input: ")
Please input: 3242
Out[53]: '3242'
In [54]: raw_input ("Please input: ")
Please input: abc
Out[54]: 'abc'

四、Python数据类型

数值  ×××int 长×××long 浮点型float(3e+4=3*10^4=30000.0)复数4-3.14j In [4]: type(3.14j)Out[4]:complex ,complex表示复数类型

序列  包括:字符串、列表、元祖,主要操作是索引操作符和切片操作符,

    索引操作符让我从序列中抓取一个特定项目

    切片操作符让我们能够获取序列的一个切片,即获取一部分    

    序列的基本操作:

     1、len()  求序列的长度

     2、+     连接2个序列

    3、*     重复序列元素

    4、in    判断元素是否在序列中

    5、max()  返回最大值

    6、min() 返回最小值

    7、com(x,y)比较两个序列是否相等


 字符串  引号表示‘’,三种方法定义字符串,str='this is a string' str="s is a string"

       str='''this is a string''' 三重引号(docstring)能定义字符串外,还可以用作注释\'


 元组   小括号表示()元组是不可变类型数据,元祖和列表十分相识,但是元组和字符串一样,

     值不可变,不能重新赋值,元组可以存一系列的值,可以索引和切片

     元组在用户定义的函数能够安全的采用一组值的时候,即被使用的元组的值不会改变

     创建元组: t= ('a',123,'12',('df',2))

            In [5]: t

            Out[5]: ('a', 123, '12', ('df', 2))


 列表   列表是可变类型的数据

       列表是处理一组有序项目的数据结构,即可在列表中存储一个序列的项目      

       创建列表:

          list1=[]

          list2=list()

          list3=['a',1,2]

      列表操作:取值,切片和索引

      添加: list.append()

      删除list元素,list3.remove(value)  删除list3的元素value,

      value=1,‘a’,list3[0]都可以,只要是这个value的值是list3的子集就可以

       删除list:del list1 

      修改:list[]=x

      查找:var in list

 


字典     字典是python中的唯一的映射类型(哈希表)

       字典对象是可变的,但字典的键必须使用不可变对象,一个字典中可以使用不同类型的键值

       字典的使用方法:

        key()   values() items()    

    创建字典:

    dic={ }

    dic=dict()  #工厂函数创建字典

    help(dict)  

    dict((['a',1],['b',2]))

    dict(a=1,b=2) #添加选项,传参数

    dict([('a',10),('b',20)]) #可迭代的对象,内部是列表或元组被传入字典

    fromekeys(),字典元素有相同的值,默认为None

    访问字典:

    dic

    dic1["a"] #a是key  

    dic1.items()# 返回时一个列表,把字典张的key和value变成一个元组里面的两个元素,保存到一个列表  

字符串的切片操作:

In [42]: a='abcde'
In [43]: a
Out[43]: 'abcde'
In [44]: a[0]
Out[44]: 'a'
In [45]: a[1]
Out[45]: 'b'
In [46]: a[4]
Out[46]: 'e'
In [47]: a[-1]
Out[47]: 'e'
In [48]: a[0]+a[1]
Out[48]: 'ab'
In [49]: a[0:2] #取值下标注0和1,不包括最后一个2
Out[49]: 'ab'
In [50]: a[:2]
Out[50]: 'ab'
In [51]: a[1:2]
Out[51]: 'b'
In [52]: a[1:]
Out[52]: 'bcde'
In [53]: a[:]
Out[53]: 'abcde'
In [54]: a[-1]
Out[54]: 'e'
In [55]: a[:-1] #从头开始,不包括最后一个-1对应的e
Out[55]: 'abcd'
In [56]: a[::1]
Out[56]: 'abcde'
In [57]: a[::2]#步进值为2
Out[57]: 'ace'
In [58]: a[::-1]#步进值-1,从后向前取值
Out[58]: 'edcba'
In [59]: a[::-2]
Out[59]: 'eca'
In [61]: a
Out[61]: 'abcde'
In [60]: a[-4:-2]
Out[60]: 'bc'
In [62]: a[-2:-4:-1] 从右到左,-2 d -3c -4b不取值,-1表示从右到左
Out[62]: 'dc'

#字符串格式化,我们用%实现,%s表示是字符类型,%.2f 表示只显示小数点后面2位,%x表示十六进制,%o表示八进制,%f默认显示小数点6位
>>> a=1.23456
>>> print "a=%s" % a
a=1.23456
>>> print "a=%.2f" % a
a=1.23
>>> print "a=%.8f" % a
a=1.23456000

#find
>>> s
'aminglinux'
>>> s.find('a')
0
>>> s.find('i')
2
#说明,find可以返回字符或子符串在整个字符串中的位置,如果有多个,只显示第一个字符或者字符串的首字符所在位置。如果不匹配,则返回-1.
>>> s1="My domain is www.aminglinux.com"
>>> s1.find('is')
10
>>> s1.find('iss')
-1
#另外,也可以在小括号里面指定两个参数,用来指定查找字符串的起始点和结束点。如果只写一个参数,则结束点就是字符串结尾。
>>> s1.find('www',2)
13
>>> s1.find('www',2,12)
-1
#说明,在字符串的2至12个中去查找是否有'www'字符串,结果是-1,因为'www'是从13开始的

#lower返回字符串的小写形式
>>> a='AmingLinux'
>>> a.lower()
'aminglinux'

#replace,替换指定字符串
>>> b='aminglinux.net'
>>> b.replace('net','com')
'aminglinux.com'

#join在字符串或者序列中定义一个连接符,把所有元素连起来,说明,f为连接符号,这样就可以在所有字符串中间用+连接起来。另外列表或元组也是可以做到的。
>>> name='aming'
>>> f='+'
>>> f.join(name)
'a+m+i+n+g'
>>> l=['a','b','c']
>>> f=':'
>>> f.join(l)
'a:b:c'
>>> l=('a','b','c')
>>> f='++'
>>> f.join(l)
'a++b++c'


#split,和join正好相反,使用指定分隔符切割字符串
>>> c='1+2+3+4+5'
>>> c.split('+')
['1', '2', '3', '4', '5']
它返回的是一个列表。

#strip,去掉字符串两边多余的空白字符,有时候我们输入一个字符串经常会无意中多加一个或多个空格,这个方法就起到作用了。
>>> e=' aaaa  bbb '
>>> e
' aaaa  bbb '
>>> e.strip()
'aaaa  bbb'


序列操作:

In [74]: a=12          #12*2=24,因为a的值是×××12
In [75]: a*2
Out[75]: 24
In [72]: a='12345'   *符号表示重复序列元素,因为a是字符串
In [73]: a*2
Out[73]: '1234512345'
In [77]: '#'*50
Out[77]: '##################################################'
In [78]: a=123 
In [79]: a+4
Out[79]: 127

In [82]: a = 'abc'
In [83]: a in a   'a' in 'abc' 判断元素是否在序列中
Out[83]: True
In [85]: 'f' in a
Out[85]: False
In [86]: 'f' not in a
Out[86]: True
In [104]: 'a' in 'abc'  
Out[104]: True
In [107]: a in 'abcde'     
Out[107]: True
In [105]: a in 'abc'    注意:'a'表示字符a,a表示字符串abc,abc 不是abd的子集,abc是abcde子集
Out[105]: True
In [106]: a in 'abd'
Out[106]: False

In [90]: a
Out[90]: 'abc'

In [91]: max(a)            #返回最大值
Out[91]: 'c'
In [92]: min(a)            #返回最小值
Out[92]: 'a'

#com(x,y)比较两个序列是否相等
In [94]: help(cmp)         #查看cmp比较命令
Help on built-in function cmp in module __builtin__:
cmp(...)
    cmp(x, y) -> integer
    Return negative if x<y, zero if x==y, positive if x>y.
    
In [96]: cmp(a,'abc')
Out[96]: 0                 #返回0表示 a='abc'

In [97]: cmp(a,'abcd')     #返回-1表示 a<'abcd'
Out[97]: -1

In [98]: cmp(a,'ab')       #返回1表示 a>'ab'
Out[98]: 1


元组定义(通常用于接收函数的返回值)、元组的拆分

In [6]: tuple3=tuple()
In [7]: type(tuple3)
Out[7]: tuple
In [107]: t=('a',1,(1,))
In [108]: t
Out[108]: ('a', 1, (1,))
In [116]: type(t)
Out[116]: tuple

In [118]: t1=(1)      #默认定义(1)为int,(1,)定义为元组tuple
In [119]: type(t1)
Out[119]: int

In [120]: t2=(1,)
In [121]: type(t2)
Out[121]: tuple

In [122]: t3=(1,t2)
In [123]: t3
Out[123]: (1, (1,))


#元组的拆分,接收元组的值
In [127]: t4=(a,'b','c')  #a表示变量a
In [128]: t4
Out[128]: ('abcd', 'b', 'c')
In [129]: first,second,third=t4  
In [130]: first
Out[130]: 'abcd'
In [131]: second
Out[131]: 'b'
In [132]: third
Out[132]: 'c'
In [142]: t4.count('abcd')  #a='abcd' 返回abcd这个字符串出现的次数1
Out[142]: 1
In [144]: t4.count(a)
Out[144]: 1
In [143]: t4.count('a')
Out[143]: 0
In [31]: t4=(a,'b','c','b') #返回d这个字符串出现的次数2

In [32]:  t4.count('b')
Out[32]: 2

Out[155]: ('abcd', 'b', 'c', 'b')
In [156]: t4.index('b')  #显示第一个b的位置
Out[156]: 1
In [157]: t4.index('c')
Out[157]: 2


列表

In [2]: list1=[]      #定义空列表
In [3]: type(list1)
Out[3]: list
In [4]: list2=list()  #定义空列表
In [5]: type(list2)
Out[5]: list
In [6]: list2
Out[6]: []
In [7]: list3=['a',1,(1,),['hello','python']]#定义列表,内容可以×××、字符串、元组、列表
In [8]: list3
Out[8]: ['a', 1, (1,), ['hello', 'python']]
In [9]: len(list3)
Out[9]: 4
In [10]: list3[0]
Out[10]: 'a'
In [11]: list3[0]='b'  #列表的值可以改变,重新赋值
In [12]: list3[0]
Out[12]: 'b'
In [13]: list3
Out[13]: ['b', 1, (1,), ['hello', 'python']]
In [14]: list2
Out[14]: []
In [15]: list2.append('linux') #使用list.append('value')添加list的值
In [17]: list2
Out[17]: ['linux']
In [18]: list3+list2           #可以让两个list相加,组合成一个大列表
Out[18]: ['b', 1, (1,), ['hello', 'python'], 'linux']
In [19]: (list3+list2)*2       #重复列表
Out[19]: 
['b',
 1,
 (1,),
 ['hello', 'python'],
 'linux',
 'b',
 1,
 (1,),
 ['hello', 'python'],
 'linux']
 
In [20]: list3
Out[20]: ['b', 1, (1,), ['hello', 'python']]
In [21]: del list3[-1]      #del list3[-1] 删除list3中的最后一个元素
In [22]: list3
Out[22]: ['b', 1, (1,)]

In [23]: list2
Out[23]: ['linux']
In [24]: del list2          #del list2直接删除list2
In [25]: list2              #list2被删除,list2查看,已经不存在
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-25-db9b7629a516> in <module>()
----> 1 list2
NameError: name 'list2' is not defined

In [28]: list3
Out[28]: ['b', 1, (1,)]
In [29]: list3.append(1)
In [30]: list3
Out[30]: ['b', 1, (1,), 1]
In [31]: list3.remove(1)   #使用list3.remove()删除第一次出现的1,从左向右
In [32]: list3
Out[32]: ['b', (1,), 1]

In [38]: 'a' in list3     #使用'a' in list3判断是否包含字符a,不包含是false,包含为true
Out[38]: False
In [39]: 'b' in list3
Out[39]: True

In [43]: help(list.insert)
insert(...)
    L.insert(index, object) -- insert object before index
In [45]: list1=list()
In [46]: list1
Out[46]: []
In [47]: list3.insert(1,list1)     #在list3的位置1处插入列表list1=[]
In [48]: list3
Out[48]: ['b', [], (1,), 1, 1]

In [55]: list3.sort()              #list3.sort()排序
In [56]: list3
Out[56]: [1, 1, [], 'b', (1,)]
In [57]: list3.reverse()           #list3.reverse()反转
In [58]: list3
Out[58]: [(1,), 'b', [], 1, 1]

In [60]: list3              
Out[60]: [(1,), 'b', [], 1, 1]
In [61]: list3.pop()               #list3.pop()默认删除最后一个
Out[61]: 1
In [62]: list3
Out[62]: [(1,), 'b', [], 1]
In [63]: list3.pop(2)              #list3.pop(2)删除第二个元素
Out[63]: []
In [64]: list3
Out[64]: [(1,), 'b', 1]


In [58]: list2
Out[58]: [2, '67', (1,), 'ab32']
In [60]: list0
Out[60]: [2, 3]
In [61]: list0.remove(list2[0])  等价于list0.remove(2)这里list2[0]=2,删除元素2
In [62]: list0
Out[62]: [3]
In [63]: list0.remove(3)
In [64]: list0
Out[64]: []
 
In [66]: help(list3.extend)        #L.extend(iterable)是可迭代的
extend(...)
    L.extend(iterable) -- extend list by appending elements from the iterable
In [67]: list3
Out[67]: [(1,), 'b', 1]

In [68]: range(5)
Out[68]: [0, 1, 2, 3, 4]
In [69]: list3.extend(range(5))  #将可迭代的range(5)的值添加到list3中
In [70]: list3
Out[70]: [(1,), 'b', 1, 0, 1, 2, 3, 4]
In [71]: list3.extend(range(2))  #将可迭代range(2)的值添加到list3中
In [72]: list3
Out[72]: [(1,), 'b', 1, 0, 1, 2, 3, 4, 0, 1]

In [73]: list3.extend('abcd')  #'abcd’被分开成可迭代的值添加到list3中
In [74]: list3
Out[74]: [(1,), 'b', 1, 0, 1, 2, 3, 4, 0, 1, 'a', 'b', 'c', 'd']
In [75]: list3.extend(('t1','t2'))#把元组中元素迭代到list3中
In [76]: list3
Out[76]: [(1,), 'b', 1, 0, 1, 2, 3, 4, 0, 1, 'a', 'b', 'c', 'd', 't1', 't2'] #

字典定义

In [14]: dic ={'a':1,1:123}
In [15]: dic 
Out[15]: {1: 123, 'a': 1}
In [16]: dic1={'a':1,1:123,('a','b'):'hello'}#定义key使用了元组('a','b')是ok的,因为元组不可变
In [17]: dic1
Out[17]: {1: 123, 'a': 1, ('a', 'b'): 'hello'}

In [18]: dic1={'a':1,1:123,['a','b']:'hello'}#定义key使用了list['a','b']是error的,因为list可变
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-8dfb0113bd5a> in <module>()
----> 1 dic1={'a':1,1:123,['a','b']:'hello'}
TypeError: unhashable type: 'list'


#字典的方法
In [25]: dic
Out[25]: {1: 123, 'a': 1}
In [26]: dic.keys()
Out[26]: ['a', 1]
In [27]: dic.values()
Out[27]: [1, 123]

In [29]: dic.
dic.clear       dic.get         dic.iteritems   dic.keys        dic.setdefault  
dic.copy        dic.has_key     dic.iterkeys    dic.pop         dic.update      
dic.fromkeys    dic.items       dic.itervalues  dic.popitem     dic.values      
In [29]: help(dic.get)
Help on built-in function get:
get(...)
    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
In [30]: dic.get('a')      #取字典中key='a'的值,返回值为no
Out[30]: 1
In [41]: dic.get('b','no') #取字典中key='b'的值,找不到就返回no
Out[41]: 'no'
In [33]: dic['a']=2        #将key=‘a’的值(value)修改为2
In [34]: dic
Out[34]: {1: 123, 'a': 2}

#判断key是不是在字典中
In [43]: 'a' in dic
Out[43]: True

In [44]: 'b' in dic
Out[44]: False

#dic.item将字典变为一个大的列表,且列表内一对key value变为一个元组,且是元组的两个元素
In [49]: dic1
Out[49]: {1: 123, 'a': 1, ('a', 'b'): 'linux'}

In [50]: dic1.items()
Out[50]: [('a', 1), (1, 123), (('a', 'b'), 'linux')]


In [49]: dic1
Out[49]: {1: 123, 'a': 1, ('a', 'b'): 'linux'}
In [51]: dic2=dic1.copy()  #dic.copy()拷贝一个字典
In [52]: dic2
Out[52]: {1: 123, 'a': 1, ('a', 'b'): 'linux'}

In [53]: dic2.clear()  #清空dic2
In [54]: dic2
Out[54]: {}

#使用dic.pop(key),返回value,然后在字典中删除该key-value
In [60]: dic1
Out[60]: {1: 123, 'a': 1, ('a', 'b'): 'linux'}

In [61]: dic1.pop(1)
Out[61]: 123

In [62]: dic1
Out[62]: {'a': 1, ('a', 'b'): 'linux'}

In [64]: dic1.pop('abc','none') #如果没有abc,则返回none
Out[64]: 'none'

#dic.update()方法,更新一个字典到另一个字典,或者将一个(k v)更新到字典
In [67]: help(dic.update)
Help on built-in function update:
update(...)
    D.update(E, **F) -> None.  Update D from dict/iterable E and F.
    If E has a .keys() method, does:     for k in E: D[k] = E[k]     #这是讲字典E的值赋值给字典D
    If E lacks .keys() method, does:     for (k, v) in E: D[k] = v   #这里是将(k,v)格式的元组,添加到字典D中
    In either case, this is followed by: for k in F: D[k] = F[k]

In [68]: dic
Out[68]: {'a': 2}
In [69]: dic1={1:1,2:2}
In [70]: dic.update(dic1) #将字典dic1得值更新到dic中
In [71]: dic
Out[71]: {1: 1, 2: 2, 'a': 2}

#创建字典
In [81]: dic={}     #创建空字典
In [82]: dic=dict()   #创建空字典
In [83]: dic
Out[83]: {}
In [86]: list1=['name','age']
In [87]: list2=['tom','20']
In [88]: zip(list1,list2)                      #合并列表
Out[88]: [('name', 'tom'), ('age', '20')]
In [89]: dict(zip(list1,list2))                #创建字典
Out[89]: {'age': '20', 'name': 'tom'}
In [90]: dict([('name', 'tom'), ('age', '20')])  #创建字典,因为是可迭代的对象,这种方法也可以
Out[90]: {'age': '20', 'name': 'tom'}
In [93]: dit5=dict(a=10,b=20)         #创建字典

#dic.fromkeys()方法,S是一个序列,[,v]是一个可选的值,可以为空也可以为value(v),默认为空
In [98]: help(dic.fromkeys)
Help on built-in function fromkeys:
fromkeys(...)
    dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
    v defaults to None.
In [99]: dic.fromkeys('abc')    #创建一个字典,序列S='abc'值为空
Out[99]: {'a': None, 'b': None, 'c': None}

In [100]: dic.fromkeys(range(5),100) #创建一个字典,S range(5),value=100
Out[100]: {0: 100, 1: 100, 2: 100, 3: 100, 4: 100}

#dic1.item()返回一个列表,把字典中的key和value变成一个元组里面的两个元素,然后保存到一个列表中
In [112]: dic1
Out[112]: {1: 1, 2: 2}
In [113]: dic1.items()
Out[113]: [(1, 1), (2, 2)]

#使用for循环访问字典dic
In [119]: for k in dic1:print k,dic1[k]
1 1
2 2
In [120]: for k in dic1:print "%s,%s" %(k,dic1[k])
1,1
2,2
In [117]: for k,v in dic1.items():print k,v 
1 1
2 2

#定义二维字典
In [129]: people={'zhangsan':{'number':1,'weight':60},'lisi':{'number':2,'weight':70}}
In [130]: people
Out[130]: {'lisi': {'number': 2, 'weight': 70}, 'zhangsan': {'number': 1, 'weight': 60}}
In [131]: people['zhangsan']
Out[131]: {'number': 1, 'weight': 60}
In [132]: people['zhangsan']['weight']
Out[132]: 60

#字典的deepcopy 拷贝
>>> a={1:'abc', 2:'def'}
>>> b=a.copy()
>>> b
{1: 'abc', 2: 'def'}
>>> b[1]='a'
>>> b
{1: 'a', 2: 'def'}
>>> a
{1: 'abc', 2: 'def'}

#当b修改一个键的值,a是不会发生影响的,但是有一种情况,是会跟着变的:

>>> a={1:'abc', 2:['d','e','f']}
>>> b=a.copy()
>>> b
{1: 'abc', 2: ['d', 'e', 'f']}
>>> b[2].remove('e')
>>> b
{1: 'abc', 2: ['d', 'f']}
>>> a
{1: 'abc', 2: ['d', 'f']}

#所以,这时候就需要用另外一种方法deepcopy

>>> from copy import deepcopy
>>> a={1:'abc', 2:['d','e','f']}
>>> c=deepcopy(a)
>>> c
{1: 'abc', 2: ['d', 'e', 'f']}
>>> c[2].remove('d')
>>> c
{1: 'abc', 2: ['e', 'f']}
>>> a
{1: 'abc', 2: ['d', 'e', 'f']}


#has_key 可以检查字典中是否存在指定的键
>>> a
{1: 'abc', 2: ['d', 'e', 'f']}
>>> a.has_key(3)
False
>>> a.has_key(2)
True

#popitem 随机获取一对键值对,并且将该键值对移除
>>> a={1:'a', 2:'b', 3:'c'}
>>> a.popitem()
(1, 'a')
>>> a.popitem()
(2, 'b')
>>> a.popitem()
(3, 'c')
>>> a
{}

#练习,将输入的name、age、gender打印出来
[root@localhost ~]# vim 4.py 

#/usr/bin/python

info = {}
name = raw_input("Please input name")
age = raw_input("Please input age")
gender = raw_input("Please input (M/F)")
info['name'] = name
info['age'] = age
info['gender'] = gender
for k,v in info.items():
    print "%s:%s" %(k,v)
   
[root@localhost ~]# python 4.py 
Please input namedavid
Please input age25
Please input (M/F)M
gender:M
age:25
name:david

表达式是将不同的数据(包括变量、函数)用运算符好号按照一定的规则连接起来的一种式子

赋值运算符





--结束END--

本文标题: python学习笔记2—python文件

本文链接: https://www.lsjlt.com/news/185757.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python学习笔记2—python文件
    python学习笔记2——python文件类型、变量、数值、字符串、元组、列表、字典一、Python文件类型1、源代码python源代码文件以.py为扩展名,由pyton程序解释,不需要编译[root@localhost day01]# v...
    99+
    2023-01-31
    学习笔记 文件 python
  • Python学习笔记(2)
    Unicode字符串: GB2312编码为表示中文产生 python内部编码是unicode编码Unicode通常用两个字节表示一个字符,原有的英文编码从单字节变成双字节,只需要把高字节全部填0 就可以以Unicode表示的字...
    99+
    2023-01-31
    学习笔记 Python
  • Python学习笔记(2)
    Python开发IDE:pycharm   ,eclipse 快捷键:Ctrl+?整体注释 一·运算符   +(加)   -(减)  *(乘)   /(除)  **(幂)  %(余)   //(商)     判断某个东西是否在某个东西里边...
    99+
    2023-01-30
    学习笔记 Python
  • Python学习笔记2——Python概
    Python概述   语言:交流的工具,沟通媒介   计算机语言:人跟计算机交流的工具,翻译官   Python是计算机语言里的一种     代码:人类语言,同过代码命令机器,跟机器交流     Python解释器: 就是那个担任翻译工作...
    99+
    2023-01-30
    学习笔记 Python
  • python学习笔记——csv文件
    目录 一、csv文件和Excel文件区别 二、手动转换(文本与列表) ①普通的写(列表嵌套转成文本的表格形式) ②普通的读(文本的表格形式转成列表嵌套)  二、csv库-读 1、CSV库-读-reader() 2、CSV库-读-D...
    99+
    2023-10-12
    python 学习 excel
  • Python第五周 学习笔记(2)
    一、实现一个cache装饰器,实现可过期被清除的功能 简化设计,函数的形参定义不包含可变位置参数、可变关键词参数和keyword-only参数 可以不考虑缓存满了之后的换出问题 1)原始 def cache(fn): imp...
    99+
    2023-01-31
    学习笔记 Python
  • Python学习笔记:第2天while循
    目录 1. while循环 continue、break和else语句 2. 格式化输出 3. 运算符 ...
    99+
    2023-01-30
    学习笔记 Python
  • python学习笔记(十)、文件操作
    在前面我们了解到了没得模块,其中有一个模块为fileinput,为文件操作模块,不知道小伙伴们是否还记得?   1 打开文件   要打开文件,可以使用fileinput中的fileinput.input函数进行打开,也可以使用模块 io ...
    99+
    2023-01-31
    学习笔记 操作 文件
  • python学习笔记(一)-文件操作
    python的基本文件操作是包含在__buildin__模块中的。   I, 基本操作1, 打开fh=open('filename', 'r')   fh是打开文件的handle,每一个被打开的文件都应该退出时关闭(除了handle没有赋给...
    99+
    2023-01-31
    学习笔记 操作 文件
  • Python学习笔记(2)比特操作、类、
    下面的笔记内容依然来自于codecademy 比特操作注意一: 适用范围 Note that you can only do bitwise operations on an integer. Trying to do them on s...
    99+
    2023-01-31
    学习笔记 操作 Python
  • Python学习日记-2
    *使用pickle处理数据存储,类似于java中的serialization,是将对象转化为二进制码存入文件中,主要函数pickle.dump(obj,file),pickle.load(file) *在每个文件加入后缀.pkl,实现逐行数...
    99+
    2023-01-31
    日记 Python
  • Python 3 学习笔记:目录&文件处
    路径 路径,用于定位目录或文件的字符串。 相对路径 相对路径依赖于当前工作目录(即当前文件所在的目录),可以使用如下函数获取当前工作目录, 1os.getcwd()复制在当前工作目录中,可以使用相对路径访问这个目录中的所有子目录和其中的文件...
    99+
    2023-01-31
    学习笔记 文件 目录
  • Python学习笔记
    Python介绍 Python是一种解释型、面向对象的语言。 官网:www.python.org Python环境 解释器:www.python.org/downloads 运行方式: 交互模式。在IDLE中运行。 脚本模式。文件的后缀...
    99+
    2023-01-30
    学习笔记 Python
  • Python 学习笔记
    rs=Person.objects.all() all返回的是QuerySet对象,程序并没有真的在数据库中执行SQL语句查询数据,但支持迭代,使用for循环可以获取数据。 print rs.query 会打印出原生sql语句 rs=Pe...
    99+
    2023-01-31
    学习笔记 Python
  • python学习笔记--趣学Python
    由反弹球和球拍构成的游戏。球会在屏幕上飞过来,玩家要用球拍把它弹回去 画布和画弹球 引入模块 #Tkinter -- Python的标准GUI库,Tk 接口,是python 内置的安装包 from tkinter import * i...
    99+
    2023-01-31
    学习笔记 python Python
  • Python学习笔记五(Python
    Python urllib模块提供了一个从指定的URL地址获取网页数据,然后对其进行分析处理,获取想要的数据。1.查看urllib模块提供的urlopen函数。help(urllib.urlopen) urlopen(url, data...
    99+
    2023-01-31
    学习笔记 Python
  • Python学习笔记四(Python
    Python os模块提供了一个统一的操作系统接口函数,通过python os模块可以实现对系统本身的命令,文件,目录进行操作,官方参考文档( http://docs.python.org/library/os)。1)os.sep 可以...
    99+
    2023-01-31
    学习笔记 Python
  • 【Python学习笔记】-Python中
    python中的格式为 为真时的结果 if 判定条件 else 为假时的结果 实例: print(1 if 5>3 else 0) 是先输出结果,再判定条件 输出1,如果5大于3,否则输出0 一般用于判断赋值中,例...
    99+
    2023-01-31
    学习笔记 Python
  • JAVA学习笔记- - - day 2
     💕前言:作者是一名正在学习JAVA的初学者,每天分享自己的学习笔记,希望能和大家一起进步成长💕 目录  💕前言:作者是一名正在学习JAVA的初学者,每天分享自己的学习笔记,希望能和...
    99+
    2023-09-04
    学习
  • python3学习笔记(2)----p
    1、python3的基本数据类型 Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在 Python 中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象的类型。等号(=)用来给...
    99+
    2023-01-31
    学习笔记
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作