创建重复N次的单个项目的列表

编程入门 行业动态 更新时间:2024-10-24 02:03:11
本文介绍了创建重复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次的单个项目的列表

本文发布于:2023-11-22 20:48:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618966.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!