如何按顺序排列n个列表(以最pythonic的方式)?

时间:2015-10-16 11:40:47

标签: python list list-comprehension

有这个:

a = 12
b = [1, 2, 3]

将它转换成这个的最pythonic方法是什么?:

[12, 1, 12, 2, 12, 3]

4 个答案:

答案 0 :(得分:4)

如果您想在ab的元素之间切换。您可以使用itertools.cyclezip,示例 -

>>> a = 12
>>> b = [1, 2, 3]
>>> from itertools import cycle
>>> [i for item in zip(cycle([a]),b) for i in item]
[12, 1, 12, 2, 12, 3]

答案 1 :(得分:1)

您可以使用itertools.repeat创建长度为b的可迭代,然后使用zip将其项目放在a的项目旁边,最后使用chain.from_iterable 1}}连接对的函数:

>>> from itertools import repeat,chain
>>> list(chain.from_iterable(zip(repeat(a,len(b)),b)))
[12, 1, 12, 2, 12, 3]

如果没有itertools,您可以使用以下技巧:

>>> it=iter(b)
>>> [next(it) if i%2==0 else a for i in range(len(b)*2)]
[1, 12, 2, 12, 3, 12]

答案 2 :(得分:1)

试试这个:

>>> a
12
>>> b
[1, 2, 3]
>>> reduce(lambda x,y:x+y,[[a] + [x] for x in b])
[12, 1, 12, 2, 12, 3]

答案 3 :(得分:0)

import itertools as it
# fillvalue, which is **a** in this case, will be zipped in tuples with,
# elements of b as long as the length of b permits.
# chain.from_iterable will then flatten the tuple list into a single list
list(it.chain.from_iterable(zip_longest([], b, fillvalue=a)))

[12, 1, 12, 2, 12, 3]