Python List:

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 ExpressionResults Description
len([1, 2, 3])3Length
[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]TrueMembership
for x in [1, 2, 3]: print x,1 2 3Iteration

 

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 ExpressionResults 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的一些相关函数:

SNFunction with Description
1cmp(list1, list2)
Compares elements of both lists.
2len(list)
Gives the total length of the list.
3max(list)
Returns item from the list with max value.
4min(list)
Returns item from the list with min value.
5list(seq)
Converts a tuple into list.

Python includes following list methods

SNMethods with Description
1list.append(obj)
Appends object obj to list
2list.count(obj)
Returns count of how many times obj occurs in list
3list.extend(seq)
Appends the contents of seq to list
4list.index(obj)
Returns the lowest index in list that obj appears
5list.insert(index, obj)
Inserts object obj into list at offset index
6list.pop(obj=list[-1])
Removes and returns last object or obj from list
7list.remove(obj)
Removes object obj from list
8list.reverse()
Reverses objects of list in place
9list.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 有什么好处呢?
  • Tuple 比 list 操作速度快。如果您定义了一个值的常量集,并且唯一要用它做的是不断地遍历它,请使用 tuple 代替 list。
  • 如果对不需要修改的数据进行 “写保护 ”,可以使代码更安全。使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句,说明这一数据是常量。如果必须要改变这些值,则需要执行 tuple 到 list 的转换 (需要使用一个特殊的函数)。
  • tuple可以作为字典的key存在,而list不行
  • Tuples 可以用在字符串格式化中,我们会很快看到。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惹不起的程咬金

来都来了,不赏点银子么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值