Python中list的一些小技巧

列表展开

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import itertools
################ case 1
a = [[1, 2], [3, 4], [5, 6]]
print list(itertools.chain.from_iterable(a))
%timeit -n 10000 list(itertools.chain.from_iterable(a))
print sum(a, [])
%timeit -n 10000 sum(a, [])
print [x for l in a for x in l]
%timeit -n 10000 [x for l in a for x in l]

# result:
# [1, 2, 3, 4, 5, 6]
# 10000 loops, best of 3: 801 ns per loop
# [1, 2, 3, 4, 5, 6]
# 10000 loops, best of 3: 359 ns per loop
# [1, 2, 3, 4, 5, 6]
# 10000 loops, best of 3: 371 ns per loop

################ case 2
b = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
[x for l1 in b for l2 in l1 for x in l2]
# [1, 2, 3, 4, 5, 6, 7, 8]

################ case 3
a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
flatten(a)
# [1, 2, 3, 4, 5, 6, 7, 8]

相邻元素压缩&依次相连

1
2
3
4
5
6
7
8
9
10
11
12
13
# python3

a = [1, 2, 3, 4, 5, 6]
list(zip(*([iter(a)] * 2)))
# [(1, 2), (3, 4), (5, 6)]
list(zip(*([iter(a)] * 3)))
# [(1, 2, 3), (4, 5, 6)]

temp = ['a', 'b', 'c', 'd', 'e','f']
list(zip(temp[:-1],temp[1:]))
# [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f')]
list(zip(temp[:-2],temp[1:-1],temp[2:]))
# [('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e'), ('d', 'e', 'f')]
-------------本文结束感谢您的阅读-------------
0%