python 入门 (二) 数字 、 字符串、元组、列表及字典

字符串

>>> a = 'a'
>>> a
'a'
>>> a = "a"
>>> a
'a'
>>> a = '''
... 123
... 123   123
...     123
...     123
... '''
>>> aaa
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'aaa' is not defined
>>> a
'\n123\n123   123\n\t123\n    123\n'
>>> print a

123
123   123
    123
    123

>>> 
>>> a = '0123456789'
>>> a[3:6]
'345'
>>> a[:6]
'012345'
>>> a[1:9:2]
'1357'
>>> a[-5:-9]
''
>>> a[-9:-5]
'1234'
>>> a[-9:-5:2]
'13'
>>> a[-9:-5:-1]
''
>>> a[9:1:-1]
'98765432'
>>> 

元组

>>> userinfo = ( 'name', 'age', 'gender' )
>>> userinfo[0]
'name'
>>> userinfo[1]
'age'
>>> userinfo[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> userinfo[2]
'gender'
>>> t = ( 1 )
>>> type( t )
<type 'int'>
>>> t = ( 1, )
>>> type( t )
<type 'tuple'>
>>> t = ()
>>> type( t )
<type 'tuple'>

元组的值不可改变

>>> name,age,gender = userinfo
>>> name
'name'
>>> age
'age'
>>> gender
'gender'
>>> a,b,c = ( 1, 2, 3 )
>>> a
1
>>> b
2
>>> c
3
>>> a = ( ( 1, 2 ), ( 3, 4 ) )
>>> a[1][1]
4

列表

>>> list = []
>>> type( list )
<type 'list'>
>>> list = [ 'pangou', 99, 'male' ]
>>> list[0:1]
['pangou']
>>> list[0:2]
['pangou', 99]
>>> list[1] = 1
>>> list
['pangou', 1, 'male']
>> id( list[0] )
3077751232L
>>> list[0] = 'opangou'
>>> id( list[0] )
3077751136L
>>> id( list )
3077744140L
>>> list[0] = 'pangou'
>>> id( list )
3077744140L
>>> list
['pangou', 1, 'male', 'shanghai']
>>> list.remove( 'shanghai' )
>>> list
['pangou', 1, 'male']
>>> list.append( 'shanghai' )
>>> list
['pangou', 1, 'male', 'shanghai']
>>> list[3]
'shanghai'
>>> list.remove( list[3] )
>>> list
['pangou', 1, 'male']

字典

>>> dict = { 'name' : 'pangou', 'age' : 99, 'gender' : 'male' }
>>> dict
{'gender': 'male', 'age': 99, 'name': 'pangou'}
>>> dict['name']
'pangou'
>>> dict['age']
99
>>> dict['gender']
'male'
>>> id( dict['name'] )
3077778848L
>>> 
>>> id( dict['age'] )
137502896
>>> id( dict['gender'] )
3077784064L
>>> type( dict )
<type 'dict'>
>>> for k in ddict:
...     print ddict[k]
... 
(1, 2)
(1, 2)
>>> 
>>> fdict = { 'a': 'a' }
>>> fdict['b'] = 'b'
>>> fdict
{'a': 'a', 'b': 'b'}
>>> fdict['c'] = 'c'
>>> fdict['d'] = 'd'
>>> fdict
{'a': 'a', 'c': 'c', 'b': 'b', 'd': 'd'}
>>> fdict.pop( 'b' )
'b'
>>> fdict
{'a': 'a', 'c': 'c', 'd': 'd'}
>>> fdict.clear()
>>> fdict
{}
>>> del fdict
>>> fdict
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fdict' is not defined
>>> 
>>> fdict = dict( x = 1, y = 2 )
>>> fdict
{'y': 2, 'x': 1}
>>> fdict.get( 'x', 2 )
1
>>> fdict.get( 'z', 2 )
2
>>> fdict.get( 'z', 3 )
3
>>> fdict.items()
[('y', 2), ('x', 1)]
原文地址:https://www.cnblogs.com/pangou/p/3113287.html