Python3基础知识之数据结构List和Tuple

问题:今天学习python数据结构中的List和Tuple。

目标:了解二者的区别,学会一般的应用


相关知识:
列表(List) : 类似于 .NET ArrayList / List。
元组(Tuple) : 列表的只读版。

1、二者之间转换:list() / tuple() 函数实现列表和元组之间进行转换。
>>>>>> a = ['a', 'b', 'c'] 
>>>>>> a 
['a', 'b', 'c'] 
>>>>>> b = tuple(a) 
>>>>>> b 
('a', 'b', 'c')
>>>>>> c = list(b) 
>>>>>> c 
['a', 'b', 'c'] 

2、二者可以接收字符串参数

url_l = list("xwy2.com")
print(url_l)
['x', 'w', 'y', '2', '.', 'c', 'o', 'm']
url_t = tuple("xwy2.com")
print(url_t)
('x', 'w', 'y', '2', '.', 'c', 'o', 'm')

3、运算符操作

>>>>>> [1, 2] * 2 
[1, 2, 1, 2] 
>>>>>> [1, 2] + [3, 4] 
[1, 2, 3, 4] 

4、in/not in 操作

可以使用 in / not in 来判断是否包含某个元素。

>>>>>> a = [1, 2, 3] 
>>>>>> 1 in a 
True 
>>>>>> 4 in a 
False 
>>>>>> b = (1, 2, 3) 
>>>>>> 2 in b 
True 

5、range()的操作

可以使用 range() 函数获得一个整数列表,甚至进行运算和添加过滤条件。

range(start, stop[, step])

>>>>>> range(10) 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>>>>> range(2, 10, 2) 
[2, 4, 6, 8] 
>>>>>> range(2, 7) 
[2, 3, 4, 5, 6] 
>>>>>> [x*2 for x in range(10)] 
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 
>>>>>> [x for x in range(10) if x%2>0] 
[1, 3, 5, 7, 9] 
>>>>>> [x + 1 for x in range(10) if x%2==0] 
[1, 3, 5, 7, 9] 


6、Slices
和字符串一样,可以通过序号或切片进行访问。

>>>>>> b = (1,2,3) 
>>>>>> b[-1] 

>>>>>> b[1:-1] 
(2,)
>>>>>> b[1] 

>>>>>> b[1:] 
(2, 3)
>>>>>> b[-1] 

>>>>>> b = [1,2,3] 
>>>>>> b[1]  = 100 
>>>>>> b 
[1, 100, 3] 

7、filter()过滤

可以使用filter() 进行过滤。

>>>>>> a = range(10) 
>>>>>> a 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>>>>> def divfilter(i): 
return i%2 == 0 

>>>>>> filter(divfilter, a) 
[0, 2, 4, 6, 8] 

简写:

>>>>>> filter(lambda i: i%2==0, range(10)) 
[0, 2, 4, 6, 8] 

当 function 参数(第一个参数)为 None 时,可以用来过滤掉空值。

>>>>>> b = ['a', '', [], [1,2]] 
>>>>>> filter(None,b) 
['a', [1, 2]] 

map() 类似 .NET 中的 Array.Foreach()

>>>>>> map(lambda i:i*2, range(10)) 
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 

可以使用 reduce() 对元素进行统计。

>>>>>> import operator 
>>>>>> reduce(operator.add, range(10)) 
45 
>>>>>> reduce(operator.sub, [100, 5, 7]) 
88 

zip() 方法可以对两个或多个列表/元组进行交叉合并

>>>>>> zip(range(2,10), ('a', 'b', 'c', 'd', 'e')) 
[(2, 'a'), (3, 'b'), (4, 'c'), (5, 'd'), (6, 'e')] 

8、其它操作

>>>>>> a = ['a','b','c'] 
>>>>>> a.index('b') 

>>>>>> a += ['d'] 
>>>>>> a 
['a', 'b', 'c', 'd'] 
>>>>>> a += ['b'] 
>>>>>> a 
['a', 'b', 'c', 'd', 'b'] 
>>>>>> a.count('b') 

>>>>>> a.insert(1, 's') 
>>>>>> a 
['a', 's', 'b', 'c', 'd', 'b'] 
>>>>>> a.remove('s') 
>>>>>> a 
['a', 'b', 'c', 'd', 'b'] 
>>>>>> a.pop(2) 
'c' 
>>>>>> a 
['a', 'b', 'd', 'b'] 
>>>>>> a.reverse() 
>>>>>> a 
['b', 'd', 'b', 'a'] 
>>>>>> a.sort() 
>>>>>> a 
['a', 'b', 'b', 'd'] 
>>>>>> a.extend(['e','f']) 
>>>>>> a 
['a', 'b', 'b', 'd', 'e', 'f'] 
>>>>>> a.append('m', 'n') 

Traceback (most recent call last): 
File "<pyshell#72>", line 6, in <module> 
a.append('m', 'n') 
TypeError: append() takes exactly one argument (2 given) 
>>>>>> a.append(['m','n']) 
>>>>>> a 
['a', 'b', 'b', 'd', 'e', 'f', ['m', 'n']] 

猜你喜欢

转载自www.cnblogs.com/johsan/p/9049639.html