python lession 2 -- data structures

本文详细介绍了Python中列表的基本操作,包括追加、插入、移除、弹出、索引、计数、排序、反转、扩展等,并通过实例展示了如何使用过滤、映射、减少函数处理列表数据。此外,还探讨了数据结构如栈、队列、矩阵、元组、集合、字典的应用,以及循环技巧。最后,文章提供了代码示例,以便读者更好地理解和实践。
  • list: append,inset,remove,pop,index,count,sort,reverse,extend
>>> list=[1,2]
>>> list.append(3)
>>> list
[1, 2, 3]
>>> list.insert(0,4)
>>> list
[4, 1, 2, 3]
>>> list.remove(1)
>>> list
[4, 2, 3]
>>> list.pop()
3
>>> list
[4, 2]
>>> list.index(4)
0
>>> list.count(4)
1
>>> list.sort()
>>> list
[2, 4]
>>> list.reverse()
>>> list
[4, 2]
>>> list.extend(list)
>>> list
[4, 2, 4, 2]
  • list as stack
>>> stack = [1,2,3]
>>> stack.append(4)
>>> stack.pop()
4
  • list as queue

caution! : "module: from collections import deque " and "constuction deque([1,2,3]) "

>>> from collections import deque
>>> queue = deque([1,2,3])
>>> queue.append(4)
>>> queue.popleft()
  • filter(),map(),and reduce():built-in function usefull for list

filter():

>>> def odd(num):
...     return num%2==1
... 
>>> filter(odd,range(0,5))
[1, 3]
  • map():
>>> def square(num):
...     return num*num
... 
>>> map(square,range(0,3))
[0, 1, 4]
  • reduce():
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
  • matrix: mutidimension array(list)
>>> matrix = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]

>>> matrix[0][0]
1

>>> zip(*matrix)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

  • del(delete)
>>> list = [1, 2, 3]
>>> del list[0]
>>> list
[2, 3]
  • tuples: separated by commas
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
  • set
>>> fruit = set(['apple','orange'])
>>> 'apple' in fruit
True
  • Dictionaries
>>> tel = {'huizhou':'0752', 'guangzhou':'020'}
>>> tel['guangzhou']
'020'
>>> 'huizhou' in tel
True
  • Looping Techniques

>>> for name,num in tel.iteritems():
...     print name, num
... 
guangzhou 020
huizhou 0752

 






转载于:https://www.cnblogs.com/chhyong88/archive/2012/02/06/2339759.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值