Python 使用筆記之 List Tuple

 

List,Tuple

1. 轉換

咱們可使用 list() / tuple() 函數在列表和元組之間進行轉換。shell

>>>>>> a = ['a', 'b', 'c']
>>>>>> a
[
'a', 'b', 'c']
>>>>>> b = tuple(a)
>>>>>> b
(
'a', 'b', 'c')('a', 'b', 'c')
>>>>>> c = list(b)
>>>>>> c
[
'a', 'b', 'c']
>>>>>>
app

這兩個函數接受字符串參數時候比較有意思。ide

>>>>>> list("xwy2.com")
[
'x', 'w', 'y', '2', '.', 'c', 'o', 'm']
>>>>>> tuple("xwy2.com")
函數

 

2. 運算符操做

列表支持運算符操做。
spa

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

 

3. in / not in

可使用 in / not in 來判斷是否包含某個元素。
ip

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

 

4. range()

咱們還可使用 range() 函數得到一個整數列表,甚至進行運算和添加過濾條件。
rem

 

>>>>>> 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]
>>>>>>
字符串

 

5. Slices

和字符串同樣,咱們能夠經過序號或切片進行訪問。

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

 

6. 相關方法

基本方法:

>>>>>> a = ['a','b','c']
>>>>>> a.index('b')
1
>>>>>> a += ['d']
>>>>>> a
[
'a', 'b', 'c', 'd']
>>>>>> a += ['b']
>>>>>> a
[
'a', 'b', 'c', 'd', 'b']
>>>>>> a.count('b')
2
>>>>>> 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 1, 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']]
>>>>>>

還可使用 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')]
>>>>>>

相關文章
相關標籤/搜索