我是靠谱客的博主 失眠秋天,最近开发中收集的这篇文章主要介绍python将一句话重复n次输出_如何仅使用itertools将Python列表的每个元素重复n次?...,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

I have a list with numbers:

numbers = [1, 2, 3, 4].

I would like to have a list where they repeat n times like so (for n = 3):

[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4].

The problem is that I would like to only use itertools for this, since I am very constrained in performance.

I tried to use this expression:

list(itertools.chain.from_iterable(itertools.repeat(numbers, 3)))

But it gives me this kind of result:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

which is obviously not what I need.

Is there a way to do this with itertools only, without using sorting, loops and list comprehensions? The closest I could get is:

list(itertools.chain.from_iterable([itertools.repeat(i, 3) for i in numbers])),

but it also uses list comprehension, which I would like to avoid.

解决方案

Since you don't want to use list comprehension, following is a pure (+zip) itertools method to do it -

from itertools import chain, repeat

list(chain.from_iterable(zip(*repeat(numbers, 3))))

# [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

最后

以上就是失眠秋天为你收集整理的python将一句话重复n次输出_如何仅使用itertools将Python列表的每个元素重复n次?...的全部内容,希望文章能够帮你解决python将一句话重复n次输出_如何仅使用itertools将Python列表的每个元素重复n次?...所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部