如何制作一个按顺序排列的 n 个列表的列表(以最 pythonic 的方式)?
How to make a list of n lists shuffled in order (in the most pythonic way possible)?
有这个:
a = 12
b = [1, 2, 3]
将它转换成这个最pythonic的方法是什么?:
[12, 1, 12, 2, 12, 3]
如果您想在 a
和 b
的元素之间交替。您可以使用 itertools.cycle
和 zip
,示例 -
>>> 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]
您可以使用 itertools.repeat
创建一个长度为 b
的可迭代对象,然后使用 zip
将它的项目放在 a
的项目旁边,最后使用chain.from_iterable
连接对的函数:
>>> 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]
试试这个:
>>> a
12
>>> b
[1, 2, 3]
>>> reduce(lambda x,y:x+y,[[a] + [x] for x in b])
[12, 1, 12, 2, 12, 3]
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]
有这个:
a = 12
b = [1, 2, 3]
将它转换成这个最pythonic的方法是什么?:
[12, 1, 12, 2, 12, 3]
如果您想在 a
和 b
的元素之间交替。您可以使用 itertools.cycle
和 zip
,示例 -
>>> 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]
您可以使用 itertools.repeat
创建一个长度为 b
的可迭代对象,然后使用 zip
将它的项目放在 a
的项目旁边,最后使用chain.from_iterable
连接对的函数:
>>> 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]
试试这个:
>>> a
12
>>> b
[1, 2, 3]
>>> reduce(lambda x,y:x+y,[[a] + [x] for x in b])
[12, 1, 12, 2, 12, 3]
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]