Tuple và List

Tuple

In [1]:
te = ()
te
Out[1]:
()
In [2]:
t = (2, 'one', 3)
t
Out[2]:
(2, 'one', 3)
In [3]:
t[0]
Out[3]:
2
In [4]:
t + (5, 6)
Out[4]:
(2, 'one', 3, 5, 6)
In [5]:
t[1] = 4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-87b0f225887f> in <module>()
----> 1 t[1] = 4

TypeError: 'tuple' object does not support item assignment
In [6]:
t[1:2]
Out[6]:
('one',)
In [7]:
t[1:3]
Out[7]:
('one', 3)
In [8]:
x = 5
y = 2
(x, y) = (y, x) # swap variable values
print('x =', x)
print('y =', y)
x = 2
y = 5
In [9]:
def quotient_and_remainder(x, y):
    q = x // y
    r = x % y
    return (q, r)

(quot, rem) = quotient_and_remainder(4, 5)
print('quotient =', quot)
print('remainder =', rem)
quotient = 0
remainder = 4
In [10]:
def get_data(aTuple):
    nums = ()
    words = ()
    for t in aTuple:
        nums = nums + (t[0],)   
        if t[1] not in words:   
            words = words + (t[1],)
    min_nums = min(nums)
    max_nums = max(nums)
    unique_words = len(words)
    return (min_nums, max_nums, unique_words)


(small, large, words) = get_data(((1, 'mine'), 
                                  (3, 'yours'),
                                  (5, 'ours'),
                                  (7, 'mine')))

print('Small =', small)
print('Large =', large)
print('Unique words = ', words)
Small = 1
Large = 7
Unique words =  3

List

In [11]:
a_list = []
a_list
Out[11]:
[]
In [12]:
b_list = [2, 'a', 4, True]
b_list
Out[12]:
[2, 'a', 4, True]
In [13]:
L = [2, 1, 3]
print(len(L))
print(L[0])
print(L[2] + 1)
print(L[3])
3
2
4
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-13-27a29de3b80b> in <module>()
      3 print(L[0])
      4 print(L[2] + 1)
----> 5 print(L[3])

IndexError: list index out of range
In [14]:
L[1] = 5
print(L)
[2, 5, 3]
In [15]:
total = 0
for i in range(len(L)):
    total += L[i]
print(total)
10
In [16]:
total = 0
for i in L:
    total += i
print(total)
10

Một số thao tác với List

Thêm

In [17]:
print(L)
[2, 5, 3]
In [18]:
L.append(5)
L
Out[18]:
[2, 5, 3, 5]
In [19]:
L1 = [2, 1, 3]
L2 = [4, 5, 6]
L3 = L1 + L2
L3
Out[19]:
[2, 1, 3, 4, 5, 6]
In [20]:
L1
Out[20]:
[2, 1, 3]
In [21]:
L2
Out[21]:
[4, 5, 6]
In [22]:
L1.extend([0, 6])
In [23]:
L1
Out[23]:
[2, 1, 3, 0, 6]

Xoá

In [24]:
del(L1[3])
L1
Out[24]:
[2, 1, 3, 6]
In [25]:
a = L1.pop()
In [26]:
L1
Out[26]:
[2, 1, 3]
In [27]:
a
Out[27]:
6
In [28]:
L = [2, 1, 3, 6, 3, 7, 0]
L.remove(2)
L
Out[28]:
[1, 3, 6, 3, 7, 0]
In [29]:
L.remove(3)
L
Out[29]:
[1, 6, 3, 7, 0]
In [30]:
del(L[1])
L
Out[30]:
[1, 3, 7, 0]
In [31]:
L.pop()
L
Out[31]:
[1, 3, 7]

Chuyển đổi thành chuỗi và ngược lại

In [32]:
s = 'I <3 cs'
list(s)
Out[32]:
['I', ' ', '<', '3', ' ', 'c', 's']
In [33]:
s.split('<')
Out[33]:
['I ', '3 cs']
In [34]:
s.split()
Out[34]:
['I', '<3', 'cs']
In [36]:
L = ['a', 'b', 'c']
''.join(L)
Out[36]:
'abc'
In [37]:
'_'.join(L)
Out[37]:
'a_b_c'

Một số thao tác khác

In [1]:
L = [9, 6 , 0, 3]
L
Out[1]:
[9, 6, 0, 3]
In [2]:
sorted(L)
Out[2]:
[0, 3, 6, 9]
In [3]:
L
Out[3]:
[9, 6, 0, 3]
In [7]:
L.sort()
L
Out[7]:
[0, 3, 6, 9]
In [5]:
L.reverse()
L
Out[5]:
[9, 6, 3, 0]

Sửa đổi, gán và sao chép - mutation, aliasing, cloning

In [20]:
warm = ['red', 'yellow', ' orange']
hot = warm # aliasing
In [21]:
hot
Out[21]:
['red', 'yellow', ' orange']
In [22]:
warm
Out[22]:
['red', 'yellow', ' orange']
In [23]:
hot.append('pink')
hot
Out[23]:
['red', 'yellow', ' orange', 'pink']
In [24]:
warm
Out[24]:
['red', 'yellow', ' orange', 'pink']
In [25]:
cool = ['blue', 'green', 'grey']
chill = ['blue', 'green', 'grey']
cool
Out[25]:
['blue', 'green', 'grey']
In [26]:
chill
Out[26]:
['blue', 'green', 'grey']
In [27]:
chill[2] = 'blue' # mutating
chill
Out[27]:
['blue', 'green', 'blue']
In [28]:
cool
Out[28]:
['blue', 'green', 'grey']
In [29]:
chill = cool[:] # cloning
chill
Out[29]:
['blue', 'green', 'grey']
In [30]:
chill.append('black')
chill
Out[30]:
['blue', 'green', 'grey', 'black']
In [31]:
warm = ['red', 'yellow', 'orange']
sortedwarm = warm.sort()
print(warm)
print(sortedwarm)
['orange', 'red', 'yellow']
None
In [32]:
cool = ['grey', 'green', 'blue']
sortedcool = sorted(cool)
print(cool)
print(sortedcool)
['grey', 'green', 'blue']
['blue', 'green', 'grey']

List of list of list

In [34]:
warm = ['yello', 'orange']
hot = ['red']
brightcolors = [warm]
brightcolors
Out[34]:
[['yello', 'orange']]
In [35]:
brightcolors.append(hot)
brightcolors
Out[35]:
[['yello', 'orange'], ['red']]
In [36]:
hot.append('pink')
print(hot)
print(brightcolors)
['red', 'pink']
[['yello', 'orange'], ['red', 'pink']]
In [37]:
print(hot + warm)
print(hot)
['red', 'pink', 'yello', 'orange']
['red', 'pink']

Mutation and Iteration

In [39]:
def remove_dups(L1, L2):
    for e in L1:
        if e in L2:
            L1.remove(e)
            
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
L1
Out[39]:
[2, 3, 4]
In [41]:
def remove_dups_new(L1, L2):
    L1_copy = L1[:] # clone
    for e in L1_copy:
        if e in L2:
            L1.remove(e)
            
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups_new(L1, L2)
L1
Out[41]:
[3, 4]

Hàm cũng là đối tượng

In [51]:
def applyToEach(L, f):
    '''
    assumes L is a list, f a function
    mutates L by replacing each element, e, of L by f(e)
    '''
    for i in range(len(L)):
        L[i] = f(L[i])
        
L = [1, -2, 3.4]
applyToEach(L, abs)
L
Out[51]:
[1, 2, 3.4]
In [52]:
applyToEach(L, int)
L
Out[52]:
[1, 2, 3]
In [53]:
def fact(n):
    if n == 1:
        return 1
    else:
        return n*fact(n-1)
    
applyToEach(L, fact)
L
Out[53]:
[1, 2, 6]
In [54]:
def fib(x):
    if x == 0 or x == 1:
        return 1
    else:
        return fib(x - 1) + fib(x - 2)

applyToEach(L, fib)
L
Out[54]:
[1, 2, 13]
In [57]:
def applyFuns(L, x):
    for f in L:
        print(f(x))
        
applyFuns([abs, int, fact, fib], 4)
4
4
24
5
In [62]:
map(abs, [1, -2, 3, -4])
Out[62]:
<map at 0x10f3ecb70>
In [61]:
for elt in map(abs, [1, -2, 3, -4]):
    print(elt)
1
2
3
4
In [63]:
L1 = [1, 28, 36]
L2 = [2, 57, 9]
for elt in map(min, L1, L2):
    print(elt)
1
28
9
In [64]:
a = []
for elt in map(abs, [1, -2, 3, -4]):
    a += [elt]
a
Out[64]:
[1, 2, 3, 4]