创建重复N次的单个项目的列表 [英] Create list of single item repeated N times

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

问题描述

我想创建一系列长度不一的列表.每个列表将包含相同的元素e,重复n次(其中n =列表的长度).

I want to create a series of lists, all of varying lengths. Each list will contain the same element e, repeated n times (where n = length of the list).

如何创建列表,而不对每个列表使用列表理解[e for number in xrange(n)]?

How do I create the lists, without using a list comprehension [e for number in xrange(n)] for each list?

推荐答案

您还可以编写:

[e] * n

您应该注意,例如,如果e是一个空列表,您将得到一个具有n个指向同一列表的引用的列表,而不是n个独立的空列表.

You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.

性能测试

乍一看,似乎重复是创建具有n个相同元素的列表的最快方法:

At first glance it seems that repeat is the fastest way to create a list with n identical elements:

>>> timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000)
0.37095273281943264
>>> timeit.timeit('[0] * 10', 'import itertools', number = 1000000)
0.5577236771712819

但是等等-这不是一个公平的测试...

But wait - it's not a fair test...

>>> itertools.repeat(0, 10)
repeat(0, 10)  # Not a list!!!

函数itertools.repeat实际上并没有创建列表,它只是创建一个对象,如果您愿意,可以使用该对象创建列表!让我们再试一次,但转换为列表:

The function itertools.repeat doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:

>>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000)
1.7508119747063233

因此,如果要列表,请使用[e] * n.如果要延迟生成元素,请使用repeat.

So if you want a list, use [e] * n. If you want to generate the elements lazily, use repeat.

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

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