1 修改python list中某个元素的值:
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print ("Value available at index 2 : ")
print (list1[2]);
list1[2] = 2001;
print ("New value available at index 2 : ")
print (list1[2]);
2 删除某个元素:
可以使用remove 或者del
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print (list1);
del list1[2];
print ("After deleting value at index 2 : ")
print (list1);
3List的基本操作:
Python Expression | Results | Description |
---|---|---|
len([1, 2, 3]) | 3 | Length |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | Concatenation |
['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | Repetition |
3 in [1, 2, 3] | True | Membership |
for x in [1, 2, 3]: print x, | 1 2 3 | Iteration |
4 list 索引操作:
Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming following input:
L = ['spam', 'Spam', 'SPAM!'] |
Python Expression | Results | Description |
---|---|---|
L[2] | 'SPAM!' | Offsets start at zero |
L[-2] | 'Spam' | Negative: count from the right |
L[1:] | ['Spam', 'SPAM!'] | Slicing fetches sections |
5 List的一些相关函数:
SN | Function with Description |
---|---|
1 | cmp(list1, list2) Compares elements of both lists. |
2 | len(list) Gives the total length of the list. |
3 | max(list) Returns item from the list with max value. |
4 | min(list) Returns item from the list with min value. |
5 | list(seq) Converts a tuple into list. |
Python includes following list methods
SN | Methods with Description |
---|---|
1 | list.append(obj) Appends object obj to list |
2 | list.count(obj) Returns count of how many times obj occurs in list |
3 | list.extend(seq) Appends the contents of seq to list |
4 | list.index(obj) Returns the lowest index in list that obj appears |
5 | list.insert(index, obj) Inserts object obj into list at offset index |
6 | list.pop(obj=list[-1]) Removes and returns last object or obj from list |
7 | list.remove(obj) Removes object obj from list |
8 | list.reverse() Reverses objects of list in place |
9 | list.sort([func]) Sorts objects of list, use compare func if given |
tuple string 都是不可修改的,但是tuple和list之间可以转换。如果有个tuple A,可用list(A)进行转换
将字符串转为list:
>>> list("hello")
['h', 'e', 'l', 'l', 'o']
使用range生成list
例如>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range函数的原型 range([lower,] stop[,step]);
>>> range(2,20,5)
[2, 7, 12, 17]
xrange([lower,] stop[,step])和range之间的区别在于:返回xrange object而不是list,仅仅在需要的时候计算list的值,节省内存。
>>> a= xrange(10)
>>> print a
xrange(10)
>>> print a[2]
利用表达式创建list:
利用for 创建:
>>> [x*x for x in range(20)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324
, 361]
>>> [a+b for a in 'AB' for b in '12']
['A1', 'A2', 'B1', 'B2']
利用if创建:
>>> [x*x for x in range(10) if x %2 ==0]
[0, 4, 16, 36, 64]
将其他的sequence类型转换为tuple
tuple(seq)
>>> tuple('tuple')
('t', 'u', 'p', 'l', 'e')
tuple和list中都允许有重复元素;
list、tuple的比较:
python会将对应的元素依次比较直到能够决定。
>>> (1,2)>(3,4)
False
>>> [1,2]<[3,4]
True
unpacking:
>>> s= 23,23,45
>>> x,y,z = s
>>> print x,y,z
23 23 45
>>> x,y,z,d =s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
注意如果unpack‘的时候需要两边变量数量相同。
filter函数:
filter函数的功能相当于过滤器。调用一个布尔函数bool_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。
filter函数python代码实现:
def filter(bool_func,seq):
filtered_seq = []
for eachItem in seq:
if bool_func(eachItem):
filtered_seq.append(eachItem)
return filtered_seq
>>>
>>> stuff = [12,0,[],[1,2]]
>>> filter(None,stuff)
[12, [1, 2]]
如果在filter中使用none,则删除为0或者空的元素
map函数:
map(func, list[,list...])
map()可以对多个序列的每个元素都执行相同的操作,并组成列表返回,声明如下:
参数func是自定义的函数,实现对序列每个元素的操作
>>> a= [1,2,3]; b=[4,5];
>>> map(None,a,b,)
[(1, 4), (2, 5), (3, None)]
if you pass in None
instead of a function,map combines the corresponding elements from each sequence and returns them as tuples
>>> import operator
>>> s = [2,3,4]; t = [4,5]
>>> map(operator.mul,s,t)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
>>> s = [2,3,4]; t = [4,5,6]
>>> map(operator.mul,s,t)
[8, 15, 24]
使用操作符的时候,list长度要相同。
Python中的reduce函数:
reduce函数,func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值。
reduct函数python代码实现:
def reduce(bin_func,seq,initial=None):
lseq = list(seq)
if initial is None:
res = lseq.pop(0)
else:
res = initial
for eachItem in lseq:
res = bin_func(res,eachItem)
return res
>>> reduce(operator.mul,[2,3,4,5])
120
zip函数:
zip(seq[,seq...])
>>> zip([1,2],[3,4,5])
[(1, 3), (2, 4)]
Ptyhon中的append 与extend:
摘自原文:
The append method adds an item to the end of a list like the += operator except that the item you pass to append is not a list. the extend method assumes the argument you pass it is a list:
关于元组:
使用 tuple 有什么好处呢?