转自http://www.cnblogs.com/soaringEveryday/p/5044007.html
List
字面意思就是一个集合,在Python中List中的元素用中括号[]来表示,可以这样定义一个List:
L = [12, \'China\', 19.998]
可以看到并不要求元素的类型都是一样的。当然也可以定义一个空的List:
L = []
Python中的List是有序的,所以要访问List的话显然要通过序号来访问,就像是数组的下标一样,一样是下标从0开始:
>>> print L[0] 12
千万不要越界,否则会报错
>>> print L[3] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
List也可以倒序访问,通过“倒数第x个”这样的下标来表示序号,比如-1这个下标就表示倒数第一个元素:
>>> L = [12, \'China\', 19.998] >>> print L[-1] 19.998
-4的话显然就越界了
>>> print L[-4] Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> print L[-4] IndexError: list index out of range >>>
List通过内置的append()方法来添加到尾部,通过insert()方法添加到指定位置(下标从0开始):
>>> L = [12, \'China\', 19.998] >>> L.append(\'Jack\') >>> print L [12, \'China\', 19.998, \'Jack\'] >>> L.insert(1, 3.14) >>> print L [12, 3.14, \'China\', 19.998, \'Jack\'] >>>
注意python中有几个方法与append类似,但是效果完全不一样,使用时需根据实际需求选用正确方法
1.append() 向列表尾部追加一个新元素,列表只占一个索引位,在原有列表上增加
2.extend() 向列表尾部追加一个列表,将列表中的每个元素都追加进来,在原有列表上增加
比如 list1=[1, 2, 3] .list2=[4, 5, 6]
list1.append(list2) 的结果为[1, 2, 3, [4, 5, 6]]
list1.extend(list2) 的结果为[1, 2, 3, 4, 5, 6]
3.+ 直接用+号看上去与用extend()一样的效果,但是实际上是生成了一个新的列表存这两个列表的和,只能用在两个列表相加上
4.+= 效果与extend()一样,向原列表追加一个新元素,在原有列表上增加
通过pop()删除最后尾部元素,也可以指定一参数删除指定位置:
>>> L.pop() \'Jack\' >>> print L [12, 3.14, \'China\', 19.998] >>> L.pop(0) 12 >>> print L [3.14, \'China\', 19.998]
也可以通过下标进行复制替换
>>> L[1] = \'America\' >>> print L [3.14, \'America\', 19.998]
Set
set也是一组数,无序,内容又不能重复,通过调用set()方法创建:
>>> s = set([\'A\', \'B\', \'C\'])
对于访问一个set的意义就仅仅在于查看某个元素是否在这个集合里面,注意大小写敏感:
>>> print \'A\' in s True >>> print \'D\' in s False
也通过for来遍历:
s = set([(\'Adam\', 95), (\'Lisa\', 85), (\'Bart\', 59)]) for x in s: print x[0],\':\',x[1] >>> Lisa : 85 Adam : 95 Bart : 59
通过add和remove来添加、删除元素(保持不重复),添加元素时,用set的add()方法
>>> s = set([1, 2, 3]) >>> s.add(4) >>> print s set([1, 2, 3, 4])
如果添加的元素已经存在于set中,add()不会报错,但是不会加进去了:
>>> s = set([1, 2, 3]) >>> s.add(3) >>> print s set([1, 2, 3])
删除set中的元素时,用set的remove()方法:
>>> s = set([1, 2, 3, 4]) >>> s.remove(4) >>> print s set([1, 2, 3])
如果删除的元素不存在set中,remove()会报错:
>>> s = set([1, 2, 3]) >>> s.remove(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 4
所以如果我们要判断一个元素是否在一些不同的条件内符合,用set是最好的选择,下面例子:
months = set([\'Jan\',\'Feb\',\'Mar\',\'Apr\',\'May\',\'Jun\',\'Jul\',\'Aug\',\'Sep\',\'Oct\',\'Nov\',\'Dec\',]) x1 = \'Feb\' x2 = \'Sun\' if x1 in months: print \'x1: ok\' else: print \'x1: error\' if x2 in months: print \'x2: ok\' else: print \'x2: error\' >>> x1: ok x2: error
另外,set的计算效率比list高,见http://www.linuxidc.com/Linux/2012-07/66404.htm