[关闭]
@guoxs 2016-03-12T14:50:19.000000Z 字数 1656 阅读 2257

python 列表与元组

python


列表

python -i filename.py 运行文件,一次输出

常用操作

对某个元素计数

  1. count(val)
  1. a=[1,2,3,4,5]
  2. print "----------- index and slice ----------"
  3. print a[0] #1
  4. print a[-1] #5
  5. print a[0:4] #[1,2,3,4]
  6. print a[0:5:2] #[1,3,5]
  7. print "------------ ref and copy -----------"
  8. a_ref=a
  9. a[2]=100
  10. print "a="+str(a) #a=[1, 2, 100, 4, 5]
  11. print "a_ref="+str(a_ref) #a_ref=[1, 2, 100, 4, 5]
  12. a_copy = a[:]
  13. print "a_copy="+str(a_copy) #a_copy=[1, 2, 100, 4, 5]
  14. print "------------ list methods ----------"
  15. a.append(300)
  16. print "After append: a="+str(a) #After append: a=[1, 2, 100, 4, 5, 300]
  17. a.insert(1,50)
  18. print "After insert: a="+str(a) #After insert: a=[1, 50, 2, 100, 4, 5, 300]
  19. a.pop()
  20. print "After pop: a="+str(a) #After pop: a=[1, 50, 2, 100, 4, 5]
  21. a.sort()
  22. print "After sort: a="+str(a) #After sort: a=[1, 2, 4, 5, 50, 100]
  23. a.reverse()
  24. print "After reverse: a="+str(a) #After reverse: a=[100, 50, 5, 4, 2, 1]
  25. del a[0]
  26. print "After del: a="+str(a) #After del: a=[50, 5, 4, 2, 1]
  27. print "------------ ref and copy ------------"
  28. print "a="+str(a) #a=[50, 5, 4, 2, 1]
  29. print "a_ref="+str(a_ref) #a_ref=[50, 5, 4, 2, 1]
  30. print "a_copy="+str(a_copy) #a_copy=[1, 2, 100, 4, 5]
  1. >>> a.count(0)
  2. 0
  3. >>> a.count(1)
  4. 1
  5. >>> s='abc'
  6. >>> s[0]
  7. File "<stdin>", line 1
  8. a[s[0]
  9. ^
  10. SyntaxError: invalid syntax
  11. >>> s[0]
  12. 'a'
  13. >>> s[0]='s'
  14. Traceback (most recent call last):
  15. File "<stdin>", line 1, in <module>
  16. TypeError: 'str' object does not support item assignment
  17. >>> s
  18. 'abc'

元组

不可变的列表,不能原处修改

表示:(a,b,c)

常用操作

  1. >>> a
  2. [50, 5, 4, 2, 1]
  3. >>> t=tuple(a)
  4. >>> t
  5. (50, 5, 4, 2, 1)
  6. >>> t[0]
  7. 50
  8. >>> t[0]=70
  9. Traceback (most recent call last):
  10. File "<stdin>", line 1, in <module>
  11. TypeError: 'tuple' object does not support item assignment
  12. >>> t.count(3)
  13. 0
  14. >>> t.count(1)
  15. 1
  16. >>> t+(1,2)
  17. (50, 5, 4, 2, 1, 1, 2)
  18. >>> t*2
  19. (50, 5, 4, 2, 1, 50, 5, 4, 2, 1)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注