[英]Trying to understand complex function
I am doing this AI project in which I need to create an array of any 5 consecutive numbers.我正在做这个 AI 项目,我需要创建一个包含任意 5 个连续数字的数组。 For example [[[1],[2],[3],[4],[5]]].
例如 [[[1],[2],[3],[4],[5]]]。 Luckily, I am following a tutorial and got this line to do it:
Data = [[[i+j] for i in range(5)] for j in range(100)]
.幸运的是,我正在关注一个教程并得到了这一行:
Data = [[[i+j] for i in range(5)] for j in range(100)]
。 I want to know what this means.我想知道这意味着什么。 I have strong knowledge of Python but have never used this type of notation.
我对 Python 有深入的了解,但从未使用过这种类型的符号。
The code编码
Data = [[[i+j] for i in range(5)] for j in range(100)]
Can be cut down to two pieces:可以切成两块:
[[i+j] for i in range(5)]
and和
[[[i+j] for i in range(5)] for j in range(100)]
Both of them contain a list comprehension .它们都包含一个列表推导。 Let's evaluate the first one.
让我们评估第一个。
[[i+j] for i in range(5)]
This is similar to:这类似于:
elements = []
for i in range(5):
elements.append([i + j])
Which produces:产生:
[[0], [1], [2], [3], [4]]
The outer loop performs this task a hundred times, but increases the inner loop start value by 1 on each run.外循环执行此任务一百次,但每次运行将内循环起始值增加 1。 So we generate 100 lists, containing a list of 5 elements, each containing a list of 1 element.
所以我们生成了 100 个列表,包含 5 个元素的列表,每个列表包含 1 个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.