刚刚提到列表是序列,所有 序列都有几种基本的操作。
>>> st=[1,2,'dflx']; >>> len(st); 3 >>> df=[6,8,"great"]; >>> st+df [1, 2, 'dflx', 6, 8, 'great'] >>> df*2; [6, 8, 'great', 6, 8, 'great'] >>> 6 in df; True >>> 2 in df False >>> num=[1,2,99,-8]; >>> max(num); 99 >>> min(num); -8
列表是不能修改的,要增加只能用相关的函数。
>>> num[4]=66; Traceback (most recent call last): File "", line 1, in IndexError: list assignment index out of range >>> num.append(66); >>> num [1, 2, 99, -8, 66]
合并二个列表用 extend();
Help on method_descriptor:
extend(...)
L.extend(iterable) -- extend list by appending elements from the iterable
>>> df=[1,2]; >>> lx=[6,8]; >>> df.extend(lx); >>> df [1, 2, 6, 8] >>> lx [6, 8]
在extend()操作中,被以字符为单位拆开(变成了列表),然后最加到列表中了。
>>> st="dflx"; >>> df.extend(st); >>> print(df); [1, 2, 6, 8, 'd', 'f', 'l', 'x']
追加整数会报错,因为extend()的参数必须是可以迭代的。
>>> a=9; >>> df.extend(a); Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable
可以得到一个结论,append()是可以整建制的追加,extend()是个体化扩编。
count()函数帮助我们弄清楚,列表中元素重复出现的次数。
Help on method_descriptor:
count(...)
L.count(value) -> integer -- return number of occurrences of value
>>> num=[1,6,3,8,5,6,2,1,3,5,1,1,2]; >>> num.count(1); 4 >>> num.count(2); 2 >>> num.count(10); 0
我的python好像见鬼了,在ubuntun中,是python3.5;
>>> num=[]; >>> num []
insert(i,x)将元素x插入到i位置。
>>> num.insert(0,'66'); >>> num ['66'] >>> num.insert(2,88); >>> num; ['66', 88]
remove(x);移除值为x的元素,不存在会报错。
>>> num.remove(88); >>> num; ['66'] >>> num.remove(0); Traceback (most recent call last): File "", line 1, in ValueError: list.remove(x): x not in list
list([i]);元括号里面的[i],表示这个参数是可以选择的,不过不写是默认删除最后一个,并将删除的元素作为返回结果。
>>> num.pop(0); '66' >>> num; []
reverse(),将列表的元素反序过来 。
>>> ch=['a','b','c']; >>> ch.reverse(); >>> ch; ['c', 'b', 'a'] sort();对列表进行排序,默认是从小到大。 >>> ch.sort(); >>> ch; ['a', 'b', 'c']
列表和字符串二中类型的对象有许多相似之处,但是也有很大区别。
相同点二者都属于序列类型,不管组成列表的元素,还是组成字符串的元素都可以从左到右,依次建立索引访问。
>>> a=[12,34,56]; >>> a[0]; 12 >>> b="abcd"; >>> b[0]; 'a'
区别列表是可以修改的,而字符串不变。
>>> a[1]='a'; >>> a.append(9); >>> a; [12, 'a', 56, 9] >>> a.insert(0,666); >>> a [666, 12, 'a', 56, 9] >>> a.remove(12); >>> a.pop(); 9 >>> b[0]='ss'; Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment
列表和字符串转换。
在一些情况下,通过split()和join()函数
str.split(),可以根据分隔符将字符串转换成列表。
>>> ch="a b c d 12 34 56";
>>> ch.split(" ");
['a', 'b', 'c', 'd', '12', '34', '56']
join可以看成split的逆运算。
```>>> a=['ab','cd','ef'];
",".join(a);
'ab,cd,ef'



