1, Lam thang 1 list
vd: 1 list nhu sau L = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]] bien no thanh dang: L = [1,2,3,4,5,6,7,8,9,10,11,12]
O day minh su dung 1 ham la reduce hoac neu ban nao dung python 3.0 tro len thi dung thu vien functools.reduce nhe:
Con day la loi giai cua bai nay:
L = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
reduce(lambda x, y: x + y, L)
hoac: functools.reduce(lambda x, y: x + y, L)
1 cach giai nua la: sum(L, [])
2, Loai bo cac phan tu trung nhau
vd: co 1 list nhu sau l = [1,2,2,1,1,1,3,3,3,4,4,6,5,4,8,] no se loai bo cac phan tu giong nhau l =[1,2,3,4,5,6,8]
o bai nay co 3 cach giai :
thu nhat : l = list(set(l))
cach thu 2;
l = dict.fromkeys(l).key()
cach thu 3: [x for i, x in enumerate(l) if i==l.index(x)]
3, Dem so phan tu co trong 1 list
dict([(x, L.count(x)) for x in set(L)])
{x: L.count(x) for x in set(L)}
import collectionscollections.Counter(L)
4, Chia 1 list thanh nhieu list
SplitInto= lambda L, n: [L[i:i+n] for i in range(0, len(L), n)]
>>> SplitInto(range(10), 3)
5, kiem tra 1 list co la tap con cua list khac
all([x in a for x in b])
http://www.vithon.org/2010/01/22/python-one-liner