重复列表的元素 n 次 [英] Repeating elements of a list n times

查看:34
本文介绍了重复列表的元素 n 次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重复列表中的每个元素 n 次并形成一个新列表?例如:

How do I repeat each element of a list n times and form a new list? For example:

x = [1,2,3,4]
n = 3

x1 = [1,1,1,2,2,2,3,3,3,4,4,4]

x * n 不起作用

for i in x[i]:
    x1 = n * x[i]

必须有一个简单而聪明的方法.

There must be a simple and smart way.

推荐答案

如果你真的想要结果作为列表,而生成器还不够:

In case you really want result as list, and generator is not sufficient:

import itertools
lst = range(1,5)
list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in lst))

Out[8]: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

这篇关于重复列表的元素 n 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆