@guoxs
2016-03-12T14:50:19.000000Z
字数 1656
阅读 2257
python
python -i filename.py 运行文件,一次输出
常用操作
del a[1]
嵌套、多种类型并存
b=[a,a_ref,a_copy]
c=[1,2,'123','abc']
运算符重载:+ *
对某个元素计数
count(val)
a=[1,2,3,4,5]
print "----------- index and slice ----------"
print a[0] #1
print a[-1] #5
print a[0:4] #[1,2,3,4]
print a[0:5:2] #[1,3,5]
print "------------ ref and copy -----------"
a_ref=a
a[2]=100
print "a="+str(a) #a=[1, 2, 100, 4, 5]
print "a_ref="+str(a_ref) #a_ref=[1, 2, 100, 4, 5]
a_copy = a[:]
print "a_copy="+str(a_copy) #a_copy=[1, 2, 100, 4, 5]
print "------------ list methods ----------"
a.append(300)
print "After append: a="+str(a) #After append: a=[1, 2, 100, 4, 5, 300]
a.insert(1,50)
print "After insert: a="+str(a) #After insert: a=[1, 50, 2, 100, 4, 5, 300]
a.pop()
print "After pop: a="+str(a) #After pop: a=[1, 50, 2, 100, 4, 5]
a.sort()
print "After sort: a="+str(a) #After sort: a=[1, 2, 4, 5, 50, 100]
a.reverse()
print "After reverse: a="+str(a) #After reverse: a=[100, 50, 5, 4, 2, 1]
del a[0]
print "After del: a="+str(a) #After del: a=[50, 5, 4, 2, 1]
print "------------ ref and copy ------------"
print "a="+str(a) #a=[50, 5, 4, 2, 1]
print "a_ref="+str(a_ref) #a_ref=[50, 5, 4, 2, 1]
print "a_copy="+str(a_copy) #a_copy=[1, 2, 100, 4, 5]
>>> a.count(0)
0
>>> a.count(1)
1
>>> s='abc'
>>> s[0]
File "<stdin>", line 1
a[s[0]
^
SyntaxError: invalid syntax
>>> s[0]
'a'
>>> s[0]='s'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> s
'abc'
不可变的列表,不能原处修改
表示:(a,b,c)
常用操作
>>> a
[50, 5, 4, 2, 1]
>>> t=tuple(a)
>>> t
(50, 5, 4, 2, 1)
>>> t[0]
50
>>> t[0]=70
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t.count(3)
0
>>> t.count(1)
1
>>> t+(1,2)
(50, 5, 4, 2, 1, 1, 2)
>>> t*2
(50, 5, 4, 2, 1, 50, 5, 4, 2, 1)