/ 猿问

# 弄平序列序列的理解？

2019-11-19 15:40:08

>>> from itertools import chain

>>> seq = '012345'

>>> swapped_pairs = zip(seq[1::2], seq[::2])

>>> swapped_pairs

[('1', '0'), ('3', '2'), ('5', '4')]

>>> "".join(chain(*swapped_pairs))

'103254'

## 3 回答

UYOU

>>> seq = '012345'

>>> swapped_pairs = zip(seq[1::2], seq[::2])

>>> ''.join(item for pair in swapped_pairs for item in pair)

'103254'

In [1]: a = [['abc', 'def'], ['ghi'],['xzy']]

In [2]: result = []

In [3]: extend = result.extend

In [4]: for l in a:

...:     extend(l)

...:

In [5]: result

Out[5]: ['abc', 'def', 'ghi', 'xzy']

\$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'

10000 loops, best of 3: 86.3 usec per loop

\$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99'  'b = []' 'extend = b.extend' 'for sub in l:' '    extend(sub)'

10000 loops, best of 3: 36.6 usec per loop

\$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]'  'b = []' 'extend = b.extend' 'for sub in l:' '    extend(sub)'

1000000 loops, best of 3: 0.844 usec per loop

\$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]' '[item for sublist in l for item in sublist]'

1000000 loops, best of 3: 1.56 usec per loop

result = [item for sublist in l for item in sublist]

result = []

for sublist in l:

for item in sublist:

result.append(item)

YMMV，但是第一个让我停滞不前，我不得不考虑一下。在第二个中，从缩进中可以明显看出嵌套。

In [6]: import operator

In [7]: a = [(1, 2), (2,3), (4,5)]

Out[8]: (1, 2, 2, 3, 4, 5)

• 3 回答
• 0 关注
• 51 浏览

0/150